![](/img/trans.png)
[英]c# extension method to define method that behaves like a static class / type method, not an instance method
[英]Extension Method of List<t> not recognize Instance method of the class C#
我有一個聯系人類,我想為該類的列表創建一個擴展方法,但它無法識別我的con.GetName()函數。 我使用正確的引用,它可以識別類名,盡管它不能識別該類的實例方法
public static string ToString (this List<Contact> Contacts)
{
string str = "";
foreach(Contact con Contacts)
{
str += con.GetName() + ", ";
}
return str.Substring(0, str.Length - 2);
}
編輯:我刪除了在功能行,但現在又有一個錯誤,這一次它標記函數的名稱(ToString),我試圖更改名稱,但沒有任何成功或更改。 現在,GetName()工作了。
Severity Code Description Project File Line Suppression State
Error CS0051 Inconsistent accessibility: parameter type 'List<Contact>' is less accessible than method 'MyExtensions.ToString(List<Contact>)' Whatsapp D:\Whatsapp Versions\17.6\Whatsapp\ExtensionMethods.cs 100 Active
這是錯字嗎? 您不小心寫了<Contact>
:
public static string ToString <Contact>(this List<Contact> Contacts)
^^^^^^^^^^
here
這使Contact
成為泛型類型參數,使您的擴展方法可在任何List<T>
。 顯然,您將無法訪問Contact
的成員,因為該列表可以是任何內容的列表。 要解決此問題,請刪除通用參數:
public static string ToString(this List<Contact> Contacts)
請注意,當您直接在List<Contact>
上調用此擴展方法時,將不會選擇該擴展方法,因為List
已具有ToString
方法(實際上所有類都可以...)。 於是打電話給你的唯一途徑ToString
是SurroundClass.ToString(someList)
我建議您重命名該方法。
您的代碼至少有兩個問題:
如果您調用擴展名ToString()
,將無法像擴展名一樣使用它,因為如果您有一個
List<Contact> myContacts = ... Console.WriteLine(myContacts.ToString());
編譯器將始終選擇List<T>
類的* instance方法ToString()
而不是您的擴展名。
您聲明了通用方法( ToString<Contact>
),當您只想在此處接受List<Contact>
時,則不需要此方法。 請注意,您在此處編寫的Contact
現在是通用類型參數,而不是您的Contact
類型。 這就是為什么編譯器不知道GetName()
方法的原因: con
不是Contact
類型,而是在編譯時不知道的泛型類型。
我建議使用string.Join
而不是“手工”連接字符串:
所以最后的建議是:
public static string AsString(this List<Contact> contacts) =>
string.Join(", ", contacts.Select(c => c.GetName());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.