继承:设置抽象字典的值

Jon*_*das 0 .net c# inheritance dictionary

我目前正在开发一个小项目,其中包括一个抽象的基类,它定义了一些需要字典的方法.然而,对于每个派生类来说,dicitionary都是个体的.

因此我在我的基类中定义了字典,如下所示:

abstract internal Dictionary<string, column> columnNames { get; }
Run Code Online (Sandbox Code Playgroud)

在每个继承类中,我设置了这样的dicitonary:

internal override Dictionary<string, column> columnNames
    {
        get
        {
            return new Dictionary<string, column>{
                {"partID", new column{ name = "ID", show = false, type = typeof(int)}},//false
                {"partName", new column{ name = "Name", show = true, type = typeof(string)}}
            };
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,如果我想更改dicitonary的属性,我尝试了以下内容:

columnNames["partID"].show = true;
Run Code Online (Sandbox Code Playgroud)

哪个不起作用.没有例外,dicitionary中的价值根本就没有机会.

我还在我的基类中编写了一个set-Function:

public void setDictEntry(string key, column value)
    {
        columnNames[key] = value;
    }
Run Code Online (Sandbox Code Playgroud)

但它仍然没有奏效.我在想:是不是因为我的字典里没有set 房产?

为了完成,这里是列类的定义:

class column
{
    public string name { get; set; }
    public bool show { get; set; }
    public string format { get; set; }
    public System.Type type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

一如既往,抱歉我的英语不好,谢谢你的帮助!

Lua*_*aan 5

当然它没有改变 - 你总是回归不同Dictonary!您必须返回现有字典(例如,通过将字典存储在字段中)以使其(有效)可变.

Dictionary<string, column> _columnNames = 
        new Dictionary<string, column>{
            {"partID", new column{ name = "ID", show = false, type = typeof(int)}},//false
            {"partName", new column{ name = "Name", show = true, type = typeof(string)}}
        };

internal override Dictionary<string, column> columnNames
{
    get
    {
        return _columnNames;
    }
}
Run Code Online (Sandbox Code Playgroud)