转换表达式<;Func<;T1>>;到表达式<;Func<;T1、T2>>;
本文关键字:lt gt T1 Func 表达式 T2 转换 | 更新日期: 2023-09-27 18:27:25
我有以下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>
。我怎样才能做到这一点?
转换表达式类型没有简单的方法。您必须重新构建整个表达式树。这不值得麻烦。有一种很好的提取公共逻辑的老方法:
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;
}
}