【发布时间】:2021-07-09 17:08:39
【问题描述】:
我正在尝试根据枚举器的实例收集应用于 IEnumerator 方法的属性。例如:
static class Program {
[SomeAttribute("Hello")]
static IEnumerator Test() {
yield return 1;
yield return "x";
}
static void Main() {
var foo = Test();
// ... How to get the attribute from the 'foo' instance?
}
}
foo.GetType()返回生成的类型Program.<Test>d__4,所以它似乎对生成它的方法有些了解。如何逆向查找Test 的 MethodInfo?从那里我可以得到属性。
我还尝试在每个方法的MethodInfo.ReturnType 属性中搜索Program 类型,以找到返回Program.<Test>d__4 的类型。令我惊讶的是,我想要的 MethodInfo 仅指示 System.Collections.IEnumerator 返回类型。
也许更了解内部原理的人可以解释我如何从生成的类型中获取 MethodInfo,反之亦然。
谢谢。
【问题讨论】:
标签: c# reflection attributes ienumerator methodinfo