How to create List of open generic type of class<T>?

梦想的初衷 提交于 2020-01-19 06:24:18

问题


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

public abstract class Data<T>
{

}

public class StringData : Data<string>
{
}

public class DecimalData : Data<decimal>
{
}

in my program i want to maintain list of different type of data

List<Data> dataCollection=new List<Data>();

dataCollection.Add(new DecimalData());
dataCollection.Add(new stringData());


List<Data> dataCollection=new List<Data>();

at above line i am getting compiler error Using the generic type 'Data' requires 1 type arguments

Can any one guide what i am doing wrong;


回答1:


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<Data<>> list = new List<Data<>>();

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<Washer<>> instance to have some Washer<Cat> and some Washer<Dog> 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<T> : IData
{
  public void SomeMethod()
  {
  }
}

List<IData> list = new List<IData>();

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<T> : DataBase
{
  public override void SomeMethod()
  {
  }
}

List<DataBase> list = new List<DataBase>();

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.




回答2:


You don't need to use generics for that.

public abstract class Data {

}

public class StringData : Data {
}

public class DecimalData : Data {
}

List<Data> dataCollection = new List<Data>();

dataCollection.Add(new DecimalData());
dataCollection.Add(new StringData());


来源:https://stackoverflow.com/questions/58570948/how-to-create-list-of-open-generic-type-of-classt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!