我有以下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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句