简体   繁体   English

创建可观察集合的通用列表派生

[英]Create Generic List derrived form Observable Collection

I want to build an ObservableCollection that derrives from the basic ObservableCollection , in order to do certain things depending on the type of the children the Collection contains. 我想建立一个ObservableCollection从基本derrives ObservableCollection ,为了做到这取决于集合包含了孩子的类型某些事情。

public class DbListBase : ObservableCollection<T>
{
    public DbListBase()
    {
        if (TypeOf(T) == Machine) {Do This}

        if (TypeOf(T) == Person) {Do That}
    }
}

However, the <T> is underlined with the errormessage Type or Namespace T not found. 但是, <T>带有下划线,并带有错误消息类型或未找到的命名空间T。

I've tried to go around it, by using a base class, which all other classes inherit, like this. 我试图通过使用所有其他类都继承的基类来解决它,就像这样。

public class DbListBase : ObservableCollection<ModelBase>
{
    public DbListBase()
    {
        // How would I check for the Type of child?
    }
}

But creating an instance of DbListBase won't let me do this: 但是创建DbListBase的实例不会让我这样做:

DbListBase MachineList = new DbListBase<Machine>();

How can I make the first approach DbListBase : ObservableCollection<T> work? 如何使第一种方法DbListBase : ObservableCollection<T>工作?

The immediate reason for your error is: your class must be generic, too: 错误的直接原因是:您的类也必须是通用的:

public class DbListBase<T> : ObservableCollection<T>
               // here ^^^^

But I don't like the idea of a generic type that does different things depending on the generic argument. 但是我不喜欢泛型类型的想法,该类型根据泛型参数执行不同的操作。 Generic should be type- independent . 泛型应与类型无关

So I'd suggest to make different derivates for each type you need it for: 因此,我建议您为每种类型使用不同的导数:

public class DbListBaseForType1 : ObservableCollection<Type1> // Type1 as generic argument for the base class
{
    // special behaviour for Type1
}

public class DbListBaseForType2 : ObservableCollection<Type2> // Type2 as generic argument for the base class
{
    // special behaviour for Type1
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM