polymorphic resolution of generic parameters in Unity registerType

前端 未结 1 831
谎友^
谎友^ 2021-01-20 21:39

I am trying to do the following and failing:

class base {}

class derived1 : base {}

class derived2 : base {}

interface itr
where t : class, base
         


        
相关标签:
1条回答
  • 2021-01-20 22:16

    You cannot do this because generics are not covariant. That is, the type itr<derived1> cannot be converted to itr<base>, even though derived1 can be converted to base.

    Here's an example of why, using the framework List<T> class:

    List<string> list1 = new List<string>();
    list1.Add("Hello, World!");
    
    // This cast will fail, because the following line would then be legal:
    List<object> list2 = (List<object>)list1; 
    
    // ints are objects, but they are not strings!
    list2.Add(1);
    

    So accessing list1[1] would return a boxed int in a list that was declared to contain strings.

    Therefore, this cast is not allowed since it would break the type system.

    (As a side note, in the clause where t : class, base, you do not need to specify class. base itself is a reference type, so the class constraint is redundant.)

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