Linq Expressions找不到公共方法...: - /

时间:2011-08-29 14:25:32

标签: .net expression dynamic-linq

我编写了一个表达式,用于测试对象的属性(枚举)是否有,或者没有设置一些标志。

下面的代码使用Enum的HasFlag函数测试对象的有效性是否“包含”星期一。

实际上,Call方法似乎找不到相应的“HasFlag”......我在下面的代码中做错了什么?

using System;
using System.Linq.Expressions;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression exp = null;

            var myValParam = Expression.Parameter(typeof(TestHehe), "val");
            var myValTestValidityParam = Expression.Property(myValParam, "TestValidity");

            Validity myVal = Validity.Monday;

            // Gives 'True'
            Console.WriteLine(myVal.HasFlag(myVal));

            // test it
            var myConst = Expression.Constant(myVal, myVal.GetType());

            // here!!!!!!!!!!!!!!!!!!!!!!!!!!
            exp = Expression.Call(myValTestValidityParam, "HasFlag", null, myConst);
            // No method 'HasFlag' on type 'ConsoleApplication3.Validity' 
            // is compatible with the supplied arguments.

            // just to be
            Console.WriteLine(exp.ToString());
        }
    }

    public class TestHehe
    {
        public Validity TestValidity { get; set; }
    }

    [Flags]
    public enum Validity
    {
        Monday = 0,
        Tuesday = 1,
        Wednesday = 2,
        Thursday = 4,
        Friday = 8,
        Saturday = 16,
        Sunday = 32
    }
}

1 个答案:

答案 0 :(得分:3)

var myConst = Expression.Constant(myVal, typeof(Enum));
// here!

exp = Expression.Call(myValTestValidityParam, "HasFlag", null, myConst);
你正在寻找这个吗? HasFlag想要Enum作为参数,因此我低估了myVal