【发布时间】:2016-05-29 20:24:17
【问题描述】:
我有几个名为SortMethod 的类继承自一个名为ASortMethod 的抽象类。这些类中的每一个都嵌套在另一个类中。现在,我正在处理名为CitationCollection 的类中的SortMethod。
我正在处理另一个名为CustomSortDictionary 的类。这必须处理给定的SortMethod 类型,但不知道会给出哪个SortMethod 类型,所以我将变量Type sortMethod 存储在CustomSortDictionary 中。
这意味着不幸的是,我不得不处理大量凌乱的反思。在给定的Type sortMethod 中,我希望访问两个主要内容。第一个我可以使用下面的代码访问,但第二个我无法访问。
BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;
// Accessing the first
MethodInfo m = SortMethod.GetMethod("ConstructCustomSortMethods", bindingFlags);
m.Invoke(null, null);
// Accessing the second
IDCollection customSort = (IDCollection)SortMethod.GetNestedType("CustomSort", bindingFlags).GetField("Methods").GetValue(null);
我尝试了BindingFlags 的几种不同组合来尝试获取第二段代码中的嵌套类型,但我无法访问它。我认为问题在于SortMethod.CustomSort.Methods 是在ASortMethod 中声明的,这比CitationCollection.SortMethod 更上一层楼。
如何使用反射正确访问第二项?
完整代码见this link。
更新:
我从微软的网站上找到了this,这可能解释了我的问题:
BindingFlags.FlattenHierarchy
指定应返回层次结构上的公共和受保护静态成员。不返回继承类中的私有静态成员。静态成员包括字段、方法、事件和属性。 不返回嵌套类型。
【问题讨论】:
-
你能提供一个可调试的例子吗?
-
@thehennyy 你的意思是一种方法?这需要很多课程才能拼出,sn-ps 或不。
-
我认为你在某个地方有这些类,所以你可以去掉所有不需要的东西,只剩下相关的部分。
-
@thehennyy 以下是我在调试时观察到的情况: 1) CitationCollection.SortMethod.CustomSort.Methods 存在; 2) (IDCollection)SortMethod.GetNestedType("CustomSort", bindingFlags).GetField("Methods").GetValue(null) 没有。如果您需要任何其他详细信息或想要完整的代码,请告诉我。
-
@thehennyy 在这里。 pastebin.com/5ShQqcFr
标签: c# reflection types nested hierarchy