mercredi 23 mars 2016

Limit a lambda expression to a simple property

The signature of my method is

void Sample<TData>(Expression<Func<TData,TValue>> expression) { }

I want to allow calls like:

Sample <MyData>(m => m.SomeProperty);

But not

Sample<MyData>(m => m.ComplexProperty.AnotherProperty);

I tried to count the number of nested bodies and limit the expression to those with a nesting count of 1, but this fails when 'SomeProperty' is derived from a base class.

private static int ItemCount(Expression lambaExpression)
{
    int itemCount = 0;
    var member = lambaExpression as MemberExpression;
    while (member != null)
    {
        itemCount += 1;
        member = member.Expression as MemberExpression;
    }
    return itemCount;
}

My question is: How do I distinguish between 'Foo.Bar' and 'Foo.Bar.Bar'?





Aucun commentaire:

Enregistrer un commentaire