【问题标题】:How to treat a dictionary of subclasses as a dictionary of the base class如何将子类字典视为基类字典
【发布时间】:2010-08-11 12:07:14
【问题描述】:

在 C# 中,我有一堆对象都继承自同一个基类。
我还有许多字典,每个子类一个。
我想要做的是将所有这些字典添加到一个 List 中,这样我就可以遍历它们并做一些工作(比如比较列表等)。

总结

Dictionary<string, Child> childObjects = new Dictionary<string, Child>();
List<Dictionary<string, Parent>> listOfDictionaries = new List<Dictionary<string, Parent>>();
listOfDictionaries.Add(childObjects);

我会认为既然 Child 继承自 Parent,这应该可以工作,但它不会编译。显然我对继承和泛型不了解:)

完整的代码示例

class Program
{
    static void Main(string[] args)
    {
        //Creating a Dictionary with a child object in it
        Dictionary<string, Child> childObjects = new Dictionary<string, Child>();
        var child = new Child();
        childObjects.Add(child.id, child);

        //Creating a "parent" Dictionary with a parent and a child object in it
        Dictionary<string, Parent> parentObjects = new Dictionary<string, Parent>();
        parentObjects.Add(child.id, child);
        var parent = new Parent();
        parentObjects.Add(parent.id, parent);

        //Adding both dictionaries to a general list
        List<Dictionary<string, Parent>> listOfDictionaries = new List<Dictionary<string, Parent>>();

        listOfDictionaries.Add(childObjects);  //This line won't compile

        listOfDictionaries.Add(parentObjects);


    }
}

class Parent
{
    public string id { get; set; }
    public Parent()
    {
        this.id = "1";
    }
}

class Child : Parent
{
    public Child()
    {
        this.id = "2";
    }

}

有什么方法可以实现吗?

【问题讨论】:

    标签: c# generics inheritance


    【解决方案1】:

    您无法安全地执行此操作。想象一下你这样做了:

    listOfDictionaries[0]["foo"] = new Parent();
    

    看起来很好 - 但这意味着 childObjects 将包含一个不是 Child 实例的值!

    C# 4 在其安全的地方引入了受限的泛型变体 - 例如,您可以将 IEnumerable&lt;Banana&gt; 类型的引用转换为 IEnumerable&lt;Fruit&gt; - 但您在这里想要做的是'不安全,所以仍然不允许。

    如果您能告诉我们更多有关更大背景的信息(您想要实现的目标),我们或许可以提供更多帮助。你能举例说明你想在之后对列表做什么吗?

    【讨论】:

    • 感谢 Jon,没想过更新。上下文是比较两组元数据的比较工具。因此,我有一个包含内容的字典列表,我只需要能够比较它们以查看它们是否包含相同的对象。比较函数是在基类上定义的,所以我会根据你的建议做的就是简单地使用 Parent[] t = childObjects.Values.ToArray();我可以遍历数组或将其转换回字典。不漂亮但足够好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2016-12-07
    • 2013-02-13
    • 1970-01-01
    • 2017-02-05
    • 2018-08-17
    相关资源
    最近更新 更多