从通用列表中查找项目 [英] Find item from generic list
问题描述
我在从通用列表中获取记录时遇到问题.我已经创建了一个通用函数,可以从任何类型的类中获取记录.下面是示例代码:-
I have a problem in fetching the record from a generic list. I have created a common function from where i want to get the records from any type of class. Below is sample code:-
public void Test<T>(List<T> rEntity) where T : class
{
object id = 1;
var result = rEntity.Where(x => x.id == id);
}
请提出建议.预先感谢.
Please suggest. Thanks in advance.
推荐答案
使用类似这样的方法,对于编译器来说,通常的问题是什么是T"?如果它只是一个类,它甚至可以是Jon提到的 StringBuilder
之类的东西,并且不能保证它具有属性'Id'.因此,它甚至无法按现在的方式进行编译.
With method like that a usual question for compiler is 'what is T' ?
If it's just a class it could be anything even a StringBuilder
as Jon has mentioned and there is no guarantee that it has a property 'Id'. So it won't even compile the way it is right now.
要使其正常运行,我们有两个选择:
To make it work we have two options :
A)更改方法,让编译器知道预期的类型
A) Change the method and let compiler know what type to expect
B)使用反射并使用运行时操作(在可能的情况下最好避免这样做,但在使用第三方库时可能会派上用场).
B) Use reflection and use run-time operations (better avoid this when possible but may come handy when working with 3rd party libraries).
A-接口解决方案:
public interface IMyInterface
{
int Id {get; set;}
}
public void Test<T>(List<T> rEntity) where T : IMyInterface
{
object id = 1;
var result = rEntity.Where(x => x.id == id);
}
B-反射解决方案:
public void Test<T>(List<T> rEntity)
{
var idProp = typeof(T).GetProperty("Id");
if(idProp != null)
{
object id = 1;
var result = rEntity.Where(x => idProp.GetValue(x).Equals(id));
}
}
这篇关于从通用列表中查找项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!