开发者

Linq Expressions does not find a public method... :-/

I write a expression that will test if a property(enum) of a object have, or have not some flags set.

The code bellow test if the validity of an object "contains" or not Monday, using the HasFlag function of an Enum.

Actually, the Call method seems do not find a corresponding "HasFlag"... What I do wrong in 开发者_JAVA百科the bellow code?

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
    }
}


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

exp = Expression.Call(myValTestValidityParam, "HasFlag", null, myConst);

Are you looking for this? HasFlag wants an Enum as the parameter, so I downcasted myVal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜