我有以下C#代码,它从lambda表达式中获取成员名:
public static class ObjectInformation<T>
{
public static string GetPropertyName<TProp>(Expression<Func<T, TProp>> propertyLambda)
{
var memberExpression = propertyLambda.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("Lambda must return a property.");
}
return memberExpression.Member.Name;
}
}
public static class ObjectInformation
{
public static string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
var memberExpression = propertyLambda.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("Lambda must return a property.");
}
return memberExpression.Member.Name;
}
}我称之为这样的方法:
ObjectInformation<RemoteCollectionContentViewModel>.GetPropertyName(e => e.SomeProperty);
ObjectInformation.GetPropertyName(() => SomeProperty)我希望第二个方法使用第一个方法(而不是复制代码),所以我需要将Func<T>转换为Func<T, TProp>。我怎样才能做到这一点?
发布于 2014-10-22 17:14:27
转换表达式类型没有简单的方法。你必须重建整个表达式树。这是不值得的麻烦。有一种很好的提取共同逻辑的老方法:
public static class ObjectInformation
{
public static string GetPropertyName<T, TProp> (Expression<Func<T, TProp>> propertyLambda)
{
return GetPropertyName((LambdaExpression)propertyLambda);
}
public static string GetPropertyName<T> (Expression<Func<T>> propertyLambda)
{
return GetPropertyName((LambdaExpression)propertyLambda);
}
private static string GetPropertyName (LambdaExpression propertyLambda)
{
var memberExpression = propertyLambda.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("Lambda must return a property.");
return memberExpression.Member.Name;
}
}https://stackoverflow.com/questions/26513091
复制相似问题