2

有什么办法可以确保我只能传入一个指向类属性的表达式?

public class Foo
{
    public string Bar { get; set; }

    public void DoSomething()
    {
        HelperClass.HelperFunc(() => Bar);
    }
}

public static class HelperClass
{
    public static void HelperFunc(Expression<Func<string>> expression)
    {
        // Ensure that the expression points to a property
        // that is a member of the class Foo (or throw exception)
    }
}

另外,如果需要,我可以更改签名以传递实际的课程......

4

1 回答 1

2

这是扩展方法,它将 lambda 转换为属性。如果 lambda 不指向属性,则抛出异常

public static PropertyInfo ToPropertyInfo(this LambdaExpression expression)
{
    MemberExpression body = expression.Body as MemberExpression;
    if (body != null)
    {
        PropertyInfo member = body.Member as PropertyInfo;
        if (member != null)
        {
            return member;
        }
    }
    throw new ArgumentException("Property not found");
}
于 2012-10-22T20:15:58.810 回答