c# - 如何获取 T 函数中使用的属性名称字符串

标签 c# parameters lambda

我有一个场景,我必须获取一个字符串数组,这些字符串表示 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/

相关文章:

c# - Entity Framework 6 异步方法与同步方法的性能

c# - 为什么下面这个简单的 Rx.NET 不打印任何数字?

android - glGetUniformLocation 调用有多快/多慢?

forEach 循环期间的 java8 java.util.ConcurrentModificationException

c# - 符号 <> 在 MSIL 中是什么意思?

c# - NullReferenceexception后收到access violation exception(0xc0000005)是否正常

c - 数组 b[] 的值如何用另一个函数的另一个数组 a[] 值填充?

excel - ByRef 参数与 Excel 中的 VBA 不匹配

python - 如何在 Python 中实现 Selenium 多个 WebDriverWait 的方法链接

Java-根据现有对象列表从流中获取新对象列表