I have a bunch of classes that all contain a Shared ReadOnly Dictionary. If I want to access that Dictionary when the class is a generic type (such as when I have a wrapper function that takes T as an interface that all of these classes implement), what’s the way to do it?
Basic research suggests I want to do something like GetType(T).GetMember("Dict"), but that will return a MemberInfo type, and that cannot be cast to a Dictionary of my defined type(s). For calling functions this way, one can use a delegate + CreateDelegate + GetMethod. But there doesn’t seem to be an equivalent Create*for GetMember stuff. Or am I missing something?
If I plug the GetMember call into the immediate window, and then use a subscript as if it is an array, then the debug output says I am getting a Dictionary back. But if I use that same approach in the actual function that I am trying to write, then I get an error about System.Reflection.MemberInfo cannot be converted to Dictionary(X, Y)
You’re nearly there.
GetMemberreturns an array of all the members with the name you pass (you can pass a string containing a wildcard*and get back multiple members). So in this case, you must index into the return value to get the actualMemberInfoyou want.Then in order to do anything with it, you’ll need to cast it to the actual
-Infotype that it is, in this case aFieldInfo.Once you’ve got a
FieldInfo, you can callGetValueon it to get the actual value of the field. You’ll need to passNothingtoGetValue, since the field is shared, so the ‘instance’ you want to get this field’s value for isn’t an instance at all.Finally you’ll need to cast the return value of
GetValueto your actual dictionary type, since it’s typed asObject.Then you can look in your dictionary.
This might seem long winded but only because I have spelled it out – if you are happy to go without error checking (which you should be, once it works), this will be a couple of lines at most.
The reason the Immediate Window ‘just works’ is because the debugger is doing all this for you behind the scenes. It’s very helpful like that.