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

时间:2013-03-05 20:35:08

标签: c# .net 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

    }

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

1 个答案:

答案 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 {
    ...
}