【问题标题】:How to use generic type inheritance in csharp如何在 csharp 中使用泛型类型继承
【发布时间】:2013-09-11 17:09:07
【问题描述】:

我有这个简单的通用代码示例:

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 存储为值的字典。 有什么帮助吗?

【问题讨论】:

  • BluePropertiesRedProperties 继承自 Properties,因此只需创建一个 Dictionary&lt;TKey, Properties&gt;
  • @AlessandroD'Andria 这不会帮助他存储RedBoxBlueBox 对象。 RedBoxBlueBox 都不是继承自 Properties
  • @cdhowie 你说得对,我不明白这个问题。

标签: c# templates generics inheritance


【解决方案1】:

对于您所描述的类型,BlueBoxRedBox 之间最近的共同祖先类型是 System.Object。您将不得不使用Dictionary&lt;TKey, object&gt;,或引入其他一些共同的祖先类型。

【讨论】:

    【解决方案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());
    

    【讨论】:

    • 事实证明这是解决我问题的正确方法。谢谢!
    【解决方案3】:

    我认为这取决于Box&lt;E&gt;的类是什么

    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

    【讨论】:

    • +1。我希望这是选择的答案,是迄今为止最好的方法
    • 这取决于类的设计,out 是限制性的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 2015-09-15
    • 2019-03-07
    • 2021-10-11
    • 2018-08-01
    • 1970-01-01
    相关资源
    最近更新 更多