类属性的泛型类型
本文关键字:泛型类型 属性 | 更新日期: 2023-09-27 18:15:06
我有以下类:
BaseField:
public abstract class BaseField {
...
public BaseField()
{
}
public BaseField(E_FieldType fieldType)
{
_FieldType = fieldType;
}
}
文本字段:
public class TextField : BaseField {
...
public TextField() : base(E_FieldType.Text)
{
}
}
DateField:
public class DateField : BaseField {
...
public DateField() : base(E_FieldType.Date)
{
}
}
和DataBlock类,其中应该包含TextField或DateField:
public class DataBlock<T> : BaseBlock where T : BaseField, new() {
...
private T _Field;
public DataBlock(string name): base(name, E_BlockType.Data)
{
_Field = new T();
}
}
下面一行可以:
DataBlock<TextField> db = new DataBlock<TextField>("qwe");
但是不可能写出这样的代码:
public ObservableCollection<DataBlock<BaseField>> DataBlockList { get; set; }
public DataBlockViewModel()
{
DataBlockList = new ObservableCollection<DataBlock<BaseField>>();
DataBlockList.Add(new DataBlock<TextField>("qwe"));
DataBlockList.Add(new DataBlock<DateField>("asd"));
}
错误是:
'BaseField'必须是具有公共无参数的非抽象类型构造函数,以便将其用作泛型类型or中的参数'T'方法
'DataBlock<T>'
请问如何解决我可以创建ObservableCollection<DataBlock<BaseField>>
collection的问题?
我可以从public class DataBlock<T> : BaseBlock where T : BaseField
和
new()
public DataBlock(string name): base(name, E_BlockType.Data)
{
//_Field = new T();
}
在本例中我可以创建DataBlockList = new ObservableCollection<DataBlock<BaseField>>();
,但不可能这样写:
DataBlockList.Add(new DataBlock<TextField>("qwe"));
DataBlockList.Add(new DataBlock<DateField>("asd"));
有两种方法可以消除错误:
1)你可以使类BaseField
非抽象
public abstract class BaseField {
...
public BaseField()
{
}
public BaseField(E_FieldType fieldType)
{
_FieldType = fieldType;
}
}
2)将新的BaseField
对象作为构造函数参数传递给DataBlock
,并删除new()
约束。
public class DataBlock<T> : BaseBlock where T : BaseField {
...
private T _Field;
public DataBlock(string name, T field): base(name, E_BlockType.Data)
{
_Field = field;
}
}