Gar*_*ush 4 c# linq generic-list
我在从通用列表中获取记录时遇到问题。我创建了一个通用函数,我想从中获取任何类型的类的记录。以下是示例代码:-
public void Test<T>(List<T> rEntity) where T : class
{
object id = 1;
var result = rEntity.Where(x => x.id == id);
}
Run Code Online (Sandbox Code Playgroud)
请建议。提前致谢。
使用这样的方法,编译器通常会问“T 是什么”?如果它只是一个类,它可以是任何东西,甚至StringBuilder是 Jon 提到的,并且不能保证它具有属性“Id”。所以它甚至不会像现在这样编译。
为了使其发挥作用,我们有两个选择:
A)更改方法并让编译器知道期望的类型
B) 使用反射并使用运行时操作(尽可能避免这种情况,但在使用第 3 方库时可能会派上用场)。
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);
}
Run Code Online (Sandbox Code Playgroud)
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));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4304 次 |
| 最近记录: |