Collection of generic types

前端 未结 9 820
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 21:06

If I have a generic class:

public class MyClass 
{
  public T Value;
}

I want to instantiate several items such as...



        
9条回答
  •  野性不改
    2020-11-27 21:15

    I think the problem here is that generic classes really aren't the same type at all. They're simply templates which create entire new types at compile time (if I understand correctly). Therefore, MyClass and MyClass are completely different types, according to the runtime. They might as well be MyIntClass and MyStringClass, which you obviously cannot have in the same list without boxing them first. They don't (necessarily) inherit the same base class, implement the same interfaces, or anything else. They're as different as any other two types out there, and you have to treat them as such (even though you think you know better).

    Of course, you can have them implement an interface, inherit a base object, or any of the other options already given. Take a look at commongenius' answer for a good way to do this.

提交回复
热议问题