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

.net dynamic-linq expression

Question

I create an expression that checks if certain flags have been set or not for an object's attribute (enum).

The code below uses an Enum's HasFlag method to determine whether or not an object "contains" Monday.

Actually, it seems that the Call method cannot locate a comparable "HasFlag"... What went wrong with the code below?

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 trying to find this?HasFlag needs anEnum as the parameter, I forecasted downwardmyVal .

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