[英]Error: Extension method must be defined in a non-generic static class
我在類名處收到以下編譯錯誤。
Extension method must be defined in a non-generic static class
我不在上普通課。 這可能是什么原因。 我不知道,也不想使用擴展方法。
根據要求,以下是我的評論作為答復:
沒有您的代碼,我們將無能為力。 我最好的猜測是您不小心在參數列表中的某個地方鍵入了“ this”。
擴展方法樣本
public static class ExtensionMethods {
public static object ToAnOtherObject(this object obj) {
// Your operation here
}
}
我遇到了同樣的問題,並按如下解決。 我的代碼是這樣的:
public static class ExtensionMethods
{
public static object ToAnOtherObject(this object obj)
{
// Your operation here
}
}
然后我將其更改為
public static class ExtensionMethods
{
public static object ToAnOtherObject(object obj)
{
// Your operation here
}
}
我刪除了方法參數的單詞“ this”。
我猜這與您以前的清單問題有關 ; 如果是這樣,我提供的示例是擴展方法,將是:
public static class LinkedListUtils { // name doesn't matter, but must be
// static and non-generic
public static IEnumerable<T> Reverse<T>(this LinkedList<T> list) {...}
}
該實用工具類不必與消費類相同,但是擴展方法是可以用作list.Reverse()
如果您不希望將其用作擴展方法,則可以將其設為本地靜態方法-只需從firstparameter中刪除“ this”即可:
public static IEnumerable<T> Reverse<T>(LinkedList<T> list) {...}
並用作:
foreach(var val in Reverse(list)) {...}
創建擴展方法時,需要考慮以下幾點:
static
static
方法 this
關鍵字。 如何發布您的代碼? 擴展方法是通過在靜態方法的第一個參數之前添加此方法來聲明的。 由於您不會使用擴展方法,因此我懷疑您不小心使用this
啟動參數列表。
尋找類似的東西:
void Method(this SomeType name)
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.