类型''不能用作泛型类型或方法中的类型参数'T' [英] 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)其中T:IFields
{
return source.Where(x => x.id == id);
}
其中 IFieds
接口是
public interface IFields
{
字符串代码{get;组; }
int id {get;组; }
}
当我尝试获取值时,显然不会编译
DB.GetByID(Helper.Database.Table< Items>(),1);
出现以下编译错误。
类型Items不能用作通用
类型或方法
中的类型参数TDB.GetByID(System.Collections.Generic.IEnumerable,int) 。
不是从Items到IFields的隐式引用转换。
我该如何解决这个问题?
实际上,我希望使用lambda表达式以匿名类型。
这个错误的明显原因消息是项目
没有实现 IFields
。
换句话说,你的 Items
类型需要这样:
public class Items:IFields
^ ----- ^
如果你不有这个,那么对于
不是有效的类型,因为它没有实现这个接口。 GetByID< T>
方法,Items
即使 Items
类型恰好具有正确的成员,情况也是如此。除非你明确指出那些成员也实现了界面,通过做我上面所展示的,这是不够的。因此,即使您的 Items
类型具有 id
属性,您仍然必须明确声明该类型实现了该接口。
I have created this generic method
public IEnumerable<T> GetByID<T>(IEnumerable<T> source, int id) where T : IFields
{
return source.Where(x => x.id == id);
}
where the IFieds
interface is
public interface IFields
{
string code { get; set; }
int id { get; set; }
}
when i try to get the value, this obviously won't compile
DB.GetByID(Helper.Database.Table<Items>(), 1);
with the following compile error.
The type "Items" cannot be used as type parameter "T" in the generic type or method "DB.GetByID(System.Collections.Generic.IEnumerable, int)". There is no implicit reference conversion from "Items" to "IFields"
How can i fix that? Actually, i wish to use lambda expression "in an anonymous type".
The obvious reason for this error message is that Items
doesn't implement IFields
.
In other words, your Items
type need to have this:
public class Items : IFields
^-----^
If you don't have this, then Items
is not a valid type for your GetByID<T>
method since it doesn't implement this interface.
This is true even if the Items
type just happens to have the right members. Unless you've explicitly stated that those members also implement the interface, by doing what I showed above, then that is not enough. So even if your Items
type have the id
property, you still have to state explicitly that the type implements the interface.
这篇关于类型''不能用作泛型类型或方法中的类型参数'T'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!