我有以下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>
。我怎么能做到这一点?
答案 0 :(得分:4)
没有简单的方法来转换表达式类型。您将不得不重建整个表达式树。这不值得麻烦。有一种很好的旧方法来提取通用逻辑:
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;
}
}