如何在csharp中使用泛型类型继承

时间:2013-09-11 17:09:08

标签: c# templates generics inheritance

我有这个示例summy通用代码:

public class Box<E> where E : BoxProperties{
}

public class BoxProperties{
}

public class BlueBox : Box<BlueBox.BlueProperties >{
    public class BlueProperties : Properties{
    }
}

public class RedBox : Box<RedBox.RedProperties >{
    public class RedProperties : Properties{
    }
}

我需要创建一个可以将RedBox和BlueBox存储为值的Dictionary。 有什么帮助吗?

3 个答案:

答案 0 :(得分:3)

根据您描述的类型,BlueBoxRedBox之间最近的共同祖先类型为System.Object。您将不得不使用Dictionary<TKey, object>,或引入其他一些共同的祖先类型。

答案 1 :(得分:2)

我认为这取决于课程Box<E>

interface IBox<out E> where E : BoxProperties
{
}

public class Box<E> : IBox<E> where E : BoxProperties
{
}

public class BoxProperties
{
}

public class BlueBox : Box<BlueBox.BlueProperties>
{
    public class BlueProperties : BoxProperties
    {
    }
}

public class RedBox : Box<RedBox.RedProperties>
{
    public class RedProperties : BoxProperties
    {
    }
}

通过这个你可以声明一个字典:

var dic = new Dictionary<string, IBox<BoxProperties>>();

dic.Add("red", new RedBox());
dic.Add("blue", new BlueBox());

但是out对您来说不是最好的,请看this

答案 2 :(得分:2)

你可以这样做 -

public class BoxProperties
{
}
interface IBox
{

}

public class Box<E> : IBox where E : BoxProperties
{
}

public class BlueBox : Box<BlueBox.BlueProperties>
{
    public class BlueProperties : BoxProperties
    {
    }
}

public class Properties
{
}

public class RedBox : Box<RedBox.RedProperties>
{
    public class RedProperties : BoxProperties
    {
    }
}

通过这个你可以做到 -

        var dictionary = new Dictionary<string, IBox>();
        dictionary.Add("a", new BlueBox());
        dictionary.Add("b", new RedBox());