首页 > 解决方案 > 字典实例覆盖

问题描述

public class Turf : Atom
{
    public Dictionary<Type, int> allowed_contents = new Dictionary<Type, int>()
    {
    };

public class Plains : Turf
{
    public new Dictionary<Type, int> allowed_contents = new Dictionary<Type, int>()
    {
        {typeof(Forest), 100},
        {typeof(Tall_Grass),  25},
        {typeof(Mountain), 10}
    };

我将如何实际覆盖allowed_contents?我确实阅读了这一点,并找到了 getter 的答案,但它涉及为每个对象创建多个字典,这不是我想要的。

标签: c#dictionary

解决方案


没有理由覆盖任何东西。您可以在构造函数中创建一个新字典:

public class Plains : Turf
{
    public Plains()
    {
        allowed_contents = new Dictionary<Type, int>()
        {
            {typeof(Forest), 100},
            {typeof(Tall_Grass),  25},
            {typeof(Mountain), 10}
        };
    }
}

推荐阅读