![](/img/trans.png)
[英]The type 'T' cannot be used as type parameter 'T' in the generic type or method
[英]The type '' cannot be used as type parameter 'T' in the generic type or method
我已經創建了這種通用方法
public IEnumerable<T> GetByID<T>(IEnumerable<T> source, int id) where T : IFields
{
return source.Where(x => x.id == id);
}
IFieds
界面在哪里
public interface IFields
{
string code { get; set; }
int id { get; set; }
}
當我嘗試獲取價值時,這顯然不會編譯
DB.GetByID(Helper.Database.Table<Items>(), 1);
以下編譯錯誤。
在通用類型或方法“ DB.GetByID(System.Collections.Generic.IEnumerable,int)”中,類型“ Items”不能用作類型參數“ T”。 沒有從“項目”到“ IFields”的隱式引用轉換
我該如何解決? 實際上,我希望“以匿名類型”使用lambda表達式。
此錯誤消息的明顯原因是Items
未實現IFields
。
換句話說,您的Items
類型需要具有以下內容:
public class Items : IFields
^-----^
如果您沒有此類型,則Items
不是您的GetByID<T>
方法的有效類型,因為它沒有實現此接口。
即使Items
類型恰好具有正確的成員,也是如此。 除非您明確聲明這些成員也通過執行上面的操作來實現該接口,否則這還不夠。 因此,即使您的Items
類型具有id
屬性,您仍然必須明確聲明該類型實現了接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.