我正在尝试创建一个列表类,以在任何属性更改时处理和引发 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 类施加这个限制?提前致谢。
最佳答案
您不能在约束中对泛型类型参数使用“或”语义,但您可以创建一个特殊接口(interface),让您的目标类型实现它,并将您的泛型实例化限制为实现特殊接口(interface)的类:
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 {
...
}
关于c# - 泛型确保 T 属于指定的 N 个类中的任何一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15233577/