gpt4 book ai didi

c# - 将表达式> 转换为表达式>

转载 作者:行者123 更新时间:2023-11-30 20:46:46 25 4
gpt4 key购买 nike

我有以下 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;
}
}

关于c# - 将表达式<Func<T1>> 转换为表达式<Func<T1, T2>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26513091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com