将lambda表达式限制为简单属性

时间:2016-03-23 07:42:55

标签: c# reflection lambda

我方法的签名是

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

我想允许这样的电话:

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

但不是

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

我尝试计算嵌套体的数量,并将表达式限制为嵌套计数为1的那些,但是当“SomeProperty”#39;源自基类。

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

我的问题是:我如何区分&#39; Foo.Bar&#39;和&#39; Foo.Bar.Bar&#39;?

1 个答案:

答案 0 :(得分:1)

类似的东西:

public static void Sample<TData, TValue>(Expression<Func<TData, TValue>> expression) 
{
    var body = expression.Body;
    var par1 = expression.Parameters[0];

    MemberExpression member = body as MemberExpression;

    if (member == null)
    {
        throw new ArgumentException();
    }

    if (member.Expression != par1)
    {
        throw new ArgumentException();
    }

    // Success
}

您只需检查Expression的{​​{1}}属性是lambda表达式的参数(MemberExpression)。