问题描述
我正在处理其他人的代码,我需要添加一些内容我上课
i am working on someone else code i need to add few thingsi 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>();
在上一行的
我遇到了编译器错误使用通用类型数据"需要1个类型参数
at above line i am getting compiler errorUsing the generic type 'Data' requires 1 type arguments
任何人都可以指导我做错了吗
Can any one guide what i am doing wrong;
推荐答案
C#中尚无Diamond运算符,因此您不能对基于封闭构造类型的开放泛型类型使用真正的多态性.
There is no diamond operator in C# yet, so you can't use true polymorphism on open generic type underlying to closed constructed types.
所以您不能创建这样的列表:
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.
例如,在C#中,您无法创建List<Washer<>>
实例来具有一些Washer<Cat>
和一些Washer<Dog>
来对它们进行操作Wash()
...
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.
这篇关于如何创建类< T>的开放通用类型的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!