Home > Back-end >  Partially typed generic objects when using reflection
Partially typed generic objects when using reflection

Time:07-20

I am trying to get fields through reflection, for example private field:

private Dictionary<string, SourceVoicePool> m_voiceHudPools;

But the class SourceVoicePool is private co I cannot use it's type and I cannot use type Dictionary<string, SourceVoicePool> in my code.

I would like to at least use for example this kind of typing:

Dictionary<string, object>

So that I can at least operate the dictionary. I am only able to get this property typed as object and then I have to use reflection to access dictionary fields and methods even though I know Dictionary class.

Can his be done better?

CodePudding user response:

All Dictionary<TKey, TValue> classes implement the non-generic interface IDictionary. If the operations in this interface are enough for your use case, use it.

FieldInfo fieldInfo = myObj.GetType().GetField("m_voiceHudPools",
    BindingFlags.NonPublic | BindingFlags.Instance);
IDictionary dict = (IDictionary)fieldInfo.GetValue(myObj, null);
object myValue = dict["myKey"];

Of course, to access the properties and method of the value object, you again have to use reflection.

CodePudding user response:

Given a class with private members and types

public class A
{
    private class B
    { public int C; }

    private Dictionary<string, B> D = new Dictionary<string, B>();
}

you can use reflection to access the type parameters of the dictionary and then call a generic method with those type parameters applied:

class Inspect
{
    public static void Reflect()
    {
        var a = new A();
        FieldInfo fieldInfo = a.GetType().GetField("D",
BindingFlags.NonPublic | BindingFlags.Instance);
        var dictionary = fieldInfo.GetValue(a);
        var dictionaryType = fieldInfo.FieldType;
        var method = DoStuff<int,int>;
        var methodInfo = method.GetMethodInfo();
        var genericMethodInfo = methodInfo.GetGenericMethodDefinition();
        var typedMethodInfo = genericMethodInfo.MakeGenericMethod(dictionaryType.GenericTypeArguments);
        typedMethodInfo.Invoke(null, new object[] { dictionary });
    }

    public static void DoStuff<T1,T2>(Dictionary<T1,T2> dictionary)
    {
        IEnumerable<T2> a = dictionary.Values;
    }
}

In the method DoStuff you now have full access to the types used for the dictionary.

  • Related