How to get the typeof(T) from a generic method with base type constraint?

前端 未结 2 467
醉话见心
醉话见心 2021-01-22 00:40

I have the following spec to help illustrate the problem:

class when_getting_type_of_generic_argument_using_subtype_instance
{
    static GenericTypeTester _gene         


        
相关标签:
2条回答
  • 2021-01-22 00:49

    Just add the constrait "class" to your method :

     class GenericTypeTester
     {
       public Type Test<T>(T dog) where T : IPet, class
       {
         return typeof (T);
       }
     }
    
    0 讨论(0)
  • 2021-01-22 01:14

    The issue here is the type being used at runtime versus compile time.

    Because you declared _dog as an IPet, the variable passed into the generic method is an IPet at compile time despite being a Dog at runtime. Thus the compiler uses IPet for the generic parameter, even though the object at runtime is a Dog. Since you used typeof(T), you get the exact type given to the generic method by the compiler.

    This can be seen by changing the type of _dog to Dog instead of IPet, which will then cause the compiler to infer the correct type.

    This can also be avoided by explicitly casting the object as dynamic:

    () => _result = _genericTypeTester.Test(_dog as dynamic);
    

    Which will force the compiler to hold off the type inference until runtime, at which point it will determine that the object is type Dog. This is generally not a good idea for production code, however, since dynamic types are rather slow.

    0 讨论(0)
提交回复
热议问题