是否可以在 c# 5.0 (.Net 4.5) 中使用 dynamic
关键字来创建动态 LINQ 查询?
我知道这可以使用第三方库,但目前不可行。
说明我的观点的最简单方法是通过示例:
class test
{
public int i { get; set; }
}
void Foo()
{
var collection = new[] { new test() { i = 1 }, new test() { i = 2 } };
Bar(collection);
}
void Bar<T>(IEnumerable<T> collection)
{
//this works
foreach (dynamic item in collection)
if (item.i == 2)
{
//do something
}
//this does not - although this is what id like to use
foreach (dynamic item in collection.Where(a => a.i == 2))
{
//do something
}
}
按请求编辑:产生编译器错误 -
'T' does not contain a definition for 'i' and no extension method 'i' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
最佳答案
替换 Bar 声明中的 T 以使用动态:
void Bar(IEnumerable<dynamic> collection)
{
//this works
foreach (dynamic item in collection)
if (item.i == 2)
{
//do something
}
//this does compile
foreach (dynamic item in collection.Where(a => a.i == 2))
{
//do something
}
}
关于c# - native 动态 Linq (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14623747/