C# 泛型确保T属于指定的N个类中的任意一个

C# 泛型确保T属于指定的N个类中的任意一个,c#,.net,generics,C#,.net,Generics,我正在尝试创建一个list类,以便在任何属性发生更改时处理和引发有关PropertyChanged的事件 我的主类包含3个列表,它们都包含3种不同类型的项 我希望能够做一些像 public class MainClass : INotifyPropertyChanged { public CustomList<TextRecord> texts{get; set;}; public CustomList<BinaryRecord> binaries{get

我正在尝试创建一个list类,以便在任何属性发生更改时处理和引发有关
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

    }
public类MainClass:INotifyPropertyChanged
{
公共自定义列表文本{get;set;};
公共自定义列表二进制文件{get;set;};
公共自定义列表MP3{get;set;};
//实现INotifyPropertyChanged
}
公共类CustomList,其中T:(TextRecord、BinaryRecord、MP3Record)
{
//代码在这里
}
请问,我怎样才能对我的CustomList类设置此限制?提前感谢。

您不能在约束中的泛型类型参数上使用“或”语义,但您可以创建特殊接口,让目标类型实现它,并将泛型实例化限制为实现特殊接口的类:

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 {
    ...
}
公共类CustomList,其中T:ICustomListable{
...
}

如果有人创建一个
CustomList
CustomList
,那么会有什么问题呢?如果你的类没有继承一个基类(全部3个)或实现一个公共接口+1,那么你就不能这样做。看到这个问题后回答是的,没有意义-这是解决这个问题的正确方法。