有什么方法可以确保我只能传入指向 a 类上的属性的表达式吗?
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)
}
}
此外,如果需要,我也可以更改签名以传递实际的类...
最佳答案
这里是扩展方法,它将 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");
}
关于c# - 确保 lambda 表达式指向类的实际属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13019049/