How to create List of open generic type of class?

后端 未结 2 348
野性不改
野性不改 2020-12-07 06:20

i am working on someone else code i need to add few things i have a class

public abstract class Data
{

}

public class StringData : Data

        
2条回答
  •  星月不相逢
    2020-12-07 07:02

    There is no diamond operator in C# yet, so you can't use true polymorphism on open generic type underlying to closed constructed types.

    Generics -Open and closed constructed Types

    Generic Classes (C# Programming Guide)

    So you can't create a list like this:

    List> list = new List>();
    

    You can't use polymorphism on such list... and it is a lack in genericity here.

    For example, in C# you can't create a List> instance to have some Washer and some Washer to operate Wash() on them...

    All you can do is using a list of objects or an ugly non generic interface pattern:

    public interface IData
    {
      void SomeMethod();
    }
    
    public abstract class Data : IData
    {
      public void SomeMethod()
      {
      }
    }
    
    List list = new List();
    
    foreach (var item in list)
      item.SomeMethod();
    

    You can also use a non generic abstract class instead of an interface:

    public abstract class DataBase
    {
      public abstract void SomeMethod();
    }
    
    public abstract class Data : DataBase
    {
      public override void SomeMethod()
      {
      }
    }
    
    List list = new List();
    
    foreach (var item in list)
      item.SomeMethod();
    

    But you lost some genericity design and strong-typing...

    And you may provide any non-generic behavior such as properties and methods you need to operate on.

提交回复
热议问题