c# - native 动态 Linq (C#)

标签 c# dynamic

是否可以在 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/

相关文章:

c# - 构造函数中的递归

javascript - 如何通过电子邮件发送动态 html 代码块?

javascript - 从 "append(<tr><td="ID 获取 ID">..."

Scala 案例类映射扩展

dynamic - C#4.0 动态对象是否有一些鸭子类型(duck typing)的功能?

c# - 如何在 asp.net c# 应用程序中放置一个可选的文件上传按钮?

c# - 如何将文本字符串转换为语音

c# - 是否可以在 vector3 中包含一个变量?

c# - 线程结束时在主线程上回调

php - 动态加载命名空间类