【问题标题】:Use reflection to find the name of a delegate field使用反射查找委托字段的名称
【发布时间】:2009-03-20 18:30:20
【问题描述】:

假设我有以下委托:

public delegate void Example();

还有一个类,如下所示:

public class TestClass {
    Example FailingTest = () => Assert.Equal(0,1);
}

如何使用反射来获得名称“FailingTest”?

到目前为止我已经尝试过:

var possibleFields = typeof(TestClass).GetFields(relevant_binding_flags)
                            .Where(x => x.FieldType.Equals(typeof(Example)));

foreach(FieldInfo oneField in possibleFields) {
  // HERE I am able to access the declaring type name
  var className = oneField.ReflectedType.Name; // == "TestClass"

  // but I am not able to access the field 
  // name "FailingTest" because:
  var fieldName = oneField.Name; // == "CS$<>9__CachedAnonymousMethodDelegate1"
}

在调试器中单步执行时,我找不到声明的字段名称“FailingTest”的路径。

该信息是在运行时保留还是在分配匿名委托时丢失?

【问题讨论】:

    标签: c# reflection delegates field


    【解决方案1】:

    你将什么BindingFlags 传递给GetFields?我用过这些:

    BindingFlags.NonPublic | BindingFlags.Instance
    

    我能够看到该字段的名称。

    【讨论】:

    • 我得到了相同的结果,使用 VS2008SP1。
    • 这对我有用;不知何故,我错过了 BindingFlags.Instance 并试图从 Type 获取此信息,然后从中读取匿名方法值;使用实例就可以了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多