字典中对象的默认值

Sco*_*ham 1 .net c# dictionary

我有一个字典设置如下: Dictionary <string, ItemProperties>

ItemProperties对象看起来像这样(基类是抽象的):

public class StringProperty : ItemProperty
{
    public string RawProp { get; set; }
    public string RenderedProp { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法像这样获取RenderedProp值(假设字典变量被称为属性):

string value = Properties[keyname];
Run Code Online (Sandbox Code Playgroud)

string value = Properties[keyname].RenderedProp;
Run Code Online (Sandbox Code Playgroud)

Rob*_*vey 5

您可以PropertyDictionary使用自定义Indexer方法创建自己的方法.

public class PropertyDictionary
{
    Dictionary <string, StringProperty> dictionary;

    public PropertyDictionary()
    {
        dictionary = new Dictionary <string, StringProperty>();
    }

    // Indexer; returns RenderedProp instead of Value
    public string this[string key]
    {
        get { return dictionary[key].RenderedProp; }
        set { dictionary[key].RenderedProp = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)