我正在尝试创建一个列表类,以便在任何属性更改时处理和引发PropertyChanged
上的事件。
我的主要课程包含3个列表,其中包含3种不同类型的项目
我希望能够做类似
的事情public class MainClass : INotifyPropertyChanged
{
public CustomList<TextRecord> texts{get; set;};
public CustomList<BinaryRecord> binaries{get; set;};
public CustomList<MP3Record> Mp3s{get; set;};
//implement INotifyPropertyChanged
}
public class CustomList<T> where T:(TextRecord, BinaryRecord, MP3Record)
{
//code goes here
}
我怎样才能将这个限制放在我的CustomList类上呢?提前谢谢。
答案 0 :(得分:12)
您不能在约束中对泛型类型参数使用“OR”语义,但您可以创建一个特殊的接口,让目标类型实现它,并将通用实例限制为实现特殊接口的类:
public interface ICustomListable {
// You can put some common properties in here
}
class TextRecord : ICustomListable {
...
}
class BinaryRecord : ICustomListable {
...
}
class MP3Record : ICustomListable {
...
}
所以现在你可以这样做:
public class CustomList<T> where T: ICustomListable {
...
}