Im相當新的C#和給自己買了一個朋友的一個項目,我有,當我試圖編譯此錯誤:如何解決'擴展方法必須在非泛型靜態類中定義'?
Extension method must be defined in a non-generic static class
的代碼如下所示:
public partial class _Default : System.Web.UI.Page {
可能是一個非常簡單的問題,但我不能弄明白。
Im相當新的C#和給自己買了一個朋友的一個項目,我有,當我試圖編譯此錯誤:如何解決'擴展方法必須在非泛型靜態類中定義'?
Extension method must be defined in a non-generic static class
的代碼如下所示:
public partial class _Default : System.Web.UI.Page {
可能是一個非常簡單的問題,但我不能弄明白。
您可能試圖在該類中定義一個extension method。
擴展方法標有static
改性劑及其與this
修改第一個參數,如:
public static void Method(this string arg) {}
如果您添加的this
修正錯誤,只需刪除它,使其正常的靜態方法。 如果您故意這樣做,請將方法聲明移至靜態非泛型非嵌套類。
嗯,它告訴你到底發生了什麼錯誤 - 你不能在非泛型靜態類以外的任何東西中放置擴展方法(一個靜態方法,其第一個參數前面有this
)。尋找其中的第一個參數是由this
前面的方法(或方法),並將其移動到一個新的,非通用靜態類:
public static class SomeExtensions
{
// Extension methods go here, e.g.
public static void SomeMethod(this SomeClass firstParam, int secondParam)
{
// ...
}
}
您正在使用的方法簽名this
關鍵字,表明它是一個extension method。
您應該創建一個static
類來包含這些方法。簽名必須是這樣的:
public static class PageExtensionMethods
{
public static void SomeMethod(this SomeType s)
{ }
}
確保雖然,你確實有意使用擴展方法。如果它只是一個你想要調用的方法,它並不一定是一個擴展方法。然後刪除this
關鍵字。
只要做到爲編者希望它應該做:
// Public static non generic class (exactly what compiler wants)
public static class PageExtensions {
...
// Your extension method for System.Web.UI.Page
public static void MyExtensionMethod(this System.Web.UI.Page value) {
...
}
}
是您打算添加至您添加的方法參數此關鍵字的擴展方法或錯誤?如果是後者,只需從參數中刪除這個關鍵字,如果前者然後[做什麼編譯器說](http://stackoverflow.com/questions/6096299/extension-methods-must-be-defined-in-a-non-generic -static級) – 2014-10-28 08:42:10