【问题标题】:Using LINQ with dynamic variables in C#在 C# 中将 LINQ 与动态变量一起使用
【发布时间】:2014-12-27 10:24:39
【问题描述】:

这是在 C# 中使用动态变量的正确方法吗?

当我尝试使用带有动态变量的 LINQ 表达式时出现以下错误。

错误 - 不能将 lambda 表达式用作动态分派操作的参数,除非先将其转换为委托或表达式树类型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic dAnimal = new Animal();
            string cc = dAnimal.x;
            Animal oAnimal = new Animal();
            var test1 = oAnimal.listFood.Where(a => a.foodName == "");
            var test2 = dAnimal.listFood.Where(a => a.foodName == "");//Error
        }
    }

    public class Animal
    {
        public string animalName {get; set;};
        public List<Food> listFood;
    }

    public class Food
    {
        public string foodName;
    }
}

【问题讨论】:

  • 你可以将 dAnimal.listFood 转换为 IEnumerable

标签: linq c#-4.0 dynamic-keyword


【解决方案1】:

我对问题的理解是dAnimal.listFood类型在编译时是未知的,因为dAnimal是动态的。所以编译器不能保证 listFood 是 IEnumerable 并且它的项目有 foodName 属性。但是,如果您将使用委托,则每个 listFood 项目将隐式转换为委托输入参数的类型(您仍然会遇到集合类型的问题)。

无论如何,在这种情况下没有任何必要使用dynamic

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    相关资源
    最近更新 更多