There is no public method in Linq Expressions...:-/

.net dynamic-linq expression

Question

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 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
    }
}
1
2
8/29/2011 2:45:56 PM

Accepted Answer

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.

3
8/29/2011 2:46:09 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow