泛型确保T是指定的N个类中的任何一个

Kob*_*kie 2 .net c# generics

我正在尝试创建一个列表类来处理和引发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

    }
Run Code Online (Sandbox Code Playgroud)

我怎样才能将这个限制放在我的CustomList类上呢?提前致谢.

das*_*ght 12

您不能在约束中对泛型类型参数使用"OR"语义,但您可以创建一个特殊的接口,让目标类型实现它,并将通用实例限制为实现特殊接口的类:

public interface ICustomListable {
    // You can put some common properties in here
}
class TextRecord : ICustomListable {
    ...
}
class BinaryRecord : ICustomListable {
    ...
}
class MP3Record : ICustomListable {
    ...
}
Run Code Online (Sandbox Code Playgroud)

所以现在你可以这样做:

public class CustomList<T> where T: ICustomListable {
    ...
}
Run Code Online (Sandbox Code Playgroud)