在 C# 中从层次结构中的较高位置获取嵌套类型
本文关键字:位置 获取 嵌套类型 层次结构 高位置 | 更新日期: 2023-09-27 18:35:16
我有几个叫做SortMethod
的类,它们继承自一个名为ASortMethod
的抽象类。这些类中的每一个都嵌套在另一个类中。现在,我正在处理一个名为 CitationCollection
的类内部的SortMethod
。
我正在处理的另一个类叫做CustomSortDictionary
。这必须处理给定的SortMethod
类型,但不知道将给出哪种SortMethod
类型,因此我在 CustomSortDictionary
中存储了一个变量Type sortMethod
。
这意味着不幸的是,我必须处理许多混乱的反思。在给定的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
向上的层次结构阶梯的一步。
如何使用反射正确访问第二项?
有关完整代码,请参阅此链接。
更新:
我从Microsoft的网站上找到了这个,这可能解释了我的问题:
BindingFlags.FlattenHierarchy
指定应返回层次结构中的公共和受保护静态成员。不返回继承类中的私有静态成员。静态成员包括字段、方法、事件和属性。不返回嵌套类型。
您的排序方法类型如下所示,对吗?
public enum SortType { Ascend, Descend, FlyingTriangle }
您可能希望使用接口,以便实现它的所有方法都需要接受或拒绝请求的排序。
例
public interface ISortable
{
public bool IsValidContext(object record, SortType type);
}
public class SortAlpha : ISortable
{
public bool IsValidContext(object record, SortType type)
{
return type == SortType.Ascend ? true : false; // example
}
}
public class SortBeta : ISortable
{
public bool IsValidContext(object record, SortType type)
{
return type == SortType.Descend && record is HtmlDocument; // example
}
}
您可以让一种方法通过实现接口的类进行迭代,以查找并返回正确的接口。
由于类型 CustomSort
总是嵌套在 ASortMethod
中,您可以直接获取它:
((IDCollection)typeof(ASortMethod.CustomSort).GetField("Methods").GetValue(null)).Add(ref name);
当您由于某种原因无法找到基本类型时,您可以向上走,直到您到达object
以找到封闭类型的CustomSort
((IDCollection)FindBase(SortMethod).GetNestedType("CustomSort", bindingFlags).GetField("Methods").GetValue(null)).Add(ref name);
static Type FindBase(Type t)
{
if (t.BaseType != typeof (object))
return FindBase(t.BaseType);
return t;
}