0

这是在 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;
    }
}
4

1 回答 1

0

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

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

于 2014-10-31T07:03:42.150 回答