mercredi 17 février 2016

Getting Nested Types from Higher in Hierarchy in C#

I have a few classes called SortMethod which inherit from an abstract class called ASortMethod. Each of these classes is nested in another class. Right now, I'm dealing with the SortMethod inside of a class called CitationCollection.

There's another class I'm dealing with called CustomSortDictionary. This has to handle the given SortMethod type, but it's unknown which SortMethod type will be given, so I store a variable Type sortMethod in CustomSortDictionary.

This means I unfortunately have to deal with lots of messy reflection. Within the given Type sortMethod, there are two main things I'm looking to access. The first I was able to access using the below code, but the second I'm having trouble getting to.

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);

I've tried a few different combinations of BindingFlags to try to get to the nested type in the second piece of code, but I can't access it. I think the issue is that SortMethod.CustomSort.Methods is declared within ASortMethod, which is one step up the hierarchical ladder from CitationCollection.SortMethod.

How would I properly access this second item using reflection?





Aucun commentaire:

Enregistrer un commentaire