存储派生对象的通用类的列表 [英] Storing list of generic class of derived objects

查看:99
本文介绍了存储派生对象的通用类的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如何存储所有使用从同一基类派生的类型的DataContainer列表.

For example, how do I store a list of DataContainers that all use types that derive from the same base class.

public class Animal {}
public class Cat : Animal {}
public class Dog : Animal {}
public class DataContainer <TData> where TData : Animal {
    TData innerObject = new TData ();
    public TData GetData () {
        return innerObject;
    }
}

public class DataManager {
    static void Main () {
        DataContainer<Cat> CatData = new DataContainer<Cat> ();
        DataContainer<Dog> DogData = new DataContainer<Dog> ();
        var AnimalData = new List<DataContainer<Animal>> ();
        AnimalData.Add (CatData);
        AnimalData.Add (DogData);
        for (int i = 0; i < AnimalData.Count; i++) {
            Animal animal = AnimalData[i].GetData ();
        }
    }
}

如果通用类无法实现,数组是否可以实现?

If it's not possible with a generic class, could it be possible with Arrays?

出现此错误:ArrayTypeMismatchException: Source array type cannot be assigned to destination array type.这将导致ArrayTypeMismatchException:

Getting this error: ArrayTypeMismatchException: Source array type cannot be assigned to destination array type. This causes an ArrayTypeMismatchException:

public interface IDataContainer <out TData> where TData : Animal {

}
public class DataContainer <TData> : IDataContainer<TData> where TData : Animal {

}

public class Tester () {
    static void Main () {
        var AnimalData = new List<DataContainer<Animal>> ();
        var CatData = new DataContainer<Cat> ();
        AnimalData.Add (CatData as IDataContainer<Animal>); //Error
    }
}

在Unity 5.2中运行

Run in Unity 5.2

推荐答案

问题是您需要通用类具有

The issue is that you need your generic class to have a covariant type parameter.

您只能在接口上执行此操作,因此创建一个:

You can only do this on interfaces, so create one:

public interface IDataContainer <out TData> where TData : Animal 
{
    TData GetData ();
}

请注意使用outTData标记为协变.现在,让您的DataContainer类实现该接口,并在客户端代码中保留引用时,请确保其为IDataContainer.现在,它应该可以让您按预期的方式存储它.

Note the use of out to mark TData as covariant. Now have your DataContainer class implement the interface, and when you hold onto a reference in the client code, make sure its an IDataContainer. Now it should let you store it as you expected.

请注意协变接口有特殊要求,即通用类型参数不能用作任何方法的参数类型(有关更多信息,请参见MSDN链接).

Do note that covariant interfaces have special requirements, namely that the generic type parameter can not be used as the argument type for any of the methods (see the MSDN link for more).

这篇关于存储派生对象的通用类的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆