Linq关于通用对象属性
你好
public T GetbyId(int id)
{
return connection.Table<T>().FirstOrDefault(x => x.Id == id);
}
我在x.id上收到错误!
i get error on the x.id!
错误 CS1061
'T'确实不包含'Id'的定义且没有扩展方法'Id'可以找到接受类型'T'的第一个参数(你是否缺少using指令或汇编引用?)
Error CS1061 'T' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
那么如何linq呢?
这是正确的。 T可能是一个没有Id属性的对象。如果你想要T具有这个属性,那么你需要在T上设置一个约束,使它实现一个具有该属性的接口,或者从一个类型派生出来。
That is correct. T is probably an object which doesn't have an Id property. If you want to require that T have this property then you need to put a constraint on T such that it implements an interface that has that property or derives from a type that does.
public interface IIdentifable
{
int Id { get; }
}
public T GetbyId<T> ( int id ) where T: IIdentifable
{
return connection.Table<T>().FirstOrDefault(x => x.Id == id);
}
您没有提供表< T>的任何上下文返回,但我认为它不是EF或类似的东西。如果它是EF,那么EF已经有一个Find方法可以完全按照你想要的方式完成,而不需要Id属性。它已经知道了PK。
对于非EF,表达式可能是更好的路径。
You didn't provide any context of what Table<T> returns but I assume it isn't EF or something like that. If it is EF then EF already has a Find method that can do exactly what you want without the need for the Id property. It already knows about PKs. For non-EF an expression might be the better route.
public T GetbyId<T> ( Func<T, bool> finder )
{
return connection.Table<T>().FirstOrDefault(x => finder(x));
}
//Usage
instance.GetbyId(x => x.Id == id);