mardi 17 janvier 2017

C# Dynamic Type Checking for Generic Objects in a Dictionary

Developing a class which has a generic dictionary of objects, with a Get method that takes the name of the object and it's desired type:

GetObjOfType(string nameOfObj, Type typeExpected);

Where typeExpected can be a base class of the type actually in the Dictionary.

When calling this method, I use the form:

MyType myObj = myDictionary.GetObjOfType("nameOfObj", Typeof(MyType)) as MyType;

In GetObjOfType, I've tried several approaches to testing if "nameOfObj" is of Type typeExpected - using the 'is' keyword and the IsAssignableFrom (from both directions - off the 'type' passed in and the Dictionary object).

But what I'm seeing is an aliasing of the passed in Typeof(MyType).

Specifically:

Dictionary<string, int> myIntegers = new Dictionary<string, int>();
myIntegers = myDictionary.GetObjOfType("myInts", Typeof(myIntegers)) as Dictionary<string, int>;
// I've also tried Typeof(Dictionary<string,int>) and myIntegers.GetType();

When I break in GetObjOfType at the line of code where 'is' or IsAssignableFrom test is, 'type' passed in to GetObjOfType is listed as:

{System.Collections.Generic.Dictionary'2[System.String, System.Int32]}

what this line of code wants to compare with is:

{System.Collections.Generic.Dictionary&lt;string,int&gt;}

I know that the 'as' keyword can be used to throw an InvalidCastException, but there's other operations I'm doing in this function and I'd really like to figure out how to resolve this aliasing issue - or at least determine if the object in myDictionary is a derived class of that specified by 'type' passed in.

Using the passed in 'type' to instance a variable to then use 'as' to catch an exception just seems too ridiculous of an approach... not sure it would work either.





Aucun commentaire:

Enregistrer un commentaire