mardi 28 juillet 2015

Reflection and Generics in C#

If I want to find the type of a parameter using the is keyword (like in this example):

private bool DoSomething<T>(HashSet<T> set)
{
    if(set is HashSet<int>) addSomeIntsTo(set);
    else if(set is HashSet<double>) addSomeDubsTo(set);

    return elementsAddToFortyTwo(set);
}

private bool elementsAddToFortyTwo<T>(HashSet<T> set)
{
    if(set is HashSet<int>) // return (sum of each number == 42);
    else if(set is HashSet<double>) // return (sum of each number == 42);
    else throw new Exception("you didn't add this type to the function");
}

...then the is keyword will return true if a strongly-typed parameter is passed in, like with:

  HashSet<int> hashset = new HashSet<int>();
  elementsAddToFortyTwo(hashset); // returns true

...but returns false if you're using a reflected type.

  HashSet<int> hashset = new HashSet<int>();
  DoSomething(hashset); // throws new Exception(), because of elementsAddToFrtyTwo(hashset)

Why is this? And, how do I make elementsAddToFortyTwo() return true when invoked in DoSomething()?





Aucun commentaire:

Enregistrer un commentaire