我有一个场景,我必须获取一个字符串数组,这些字符串表示 Func 参数中使用的每个属性名称。这是一个示例实现:
public class CustomClass<TSource>
{
public string[] GetPropertiesUsed
{
get
{
// do magical parsing based upon parameter passed into CustomMethod
}
}
public void CustomMethod(Func<TSource, object> method)
{
// do stuff
}
}
这是一个示例用法:
var customClass = new CustomClass<Person>();
customClass.CustomMethod(src => "(" + src.AreaCode + ") " + src.Phone);
...
var propertiesUsed = customClass.GetPropertiesUsed;
// propertiesUsed should contain ["AreaCode", "Phone"]
我在上面坚持的部分是“根据传递给 CustomMethod 的参数进行神奇的解析。”
最佳答案
你应该使用 Expression<Func<>>
类代替。该表达式包含实际的树,并且可以很容易地进行编译以获取委托(delegate)(这是一个函数)。您真正要做的是查看表达式的主体并对其进行推理。表达式类为您提供所有必要的基础设施。
关于c# - 如何获取 T 函数中使用的属性名称字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4726565/