C#模仿Python字典语法的方式

Wal*_*t W 12 c# python syntax dictionary types

有没有一种很好的方法在C#中模仿以下python语法:

mydict = {}
mydict["bc"] = {}
mydict["bc"]["de"] = "123";  # <-- This line
mydict["te"] = "5";          # <-- While also allowing this line
Run Code Online (Sandbox Code Playgroud)

换句话说,我想要[]样式访问的东西可以返回另一个字典或字符串类型,具体取决于它的设置方式.

我一直试图用自定义类来解决这个问题,但似乎无法成功.有任何想法吗?

谢谢!

编辑:我知道,我是邪恶的.Jared Par的解决方案很棒...对于此表单的2级字典.但是,我也对进一步的水平感到好奇...例如,

mydict["bc"]["df"]["ic"] = "32";
Run Code Online (Sandbox Code Playgroud)

等等.关于那个的任何想法?

编辑3:

这是我最终使用的最后一堂课:

class PythonDict {
    /* Public properties and conversions */
    public PythonDict this[String index] {
        get {
            return this.dict_[index];
        }
        set {
            this.dict_[index] = value;
        }
    }

    public static implicit operator PythonDict(String value) {
        return new PythonDict(value);
    }

    public static implicit operator String(PythonDict value) {
        return value.str_;
    }

    /* Public methods */
    public PythonDict() {
        this.dict_ = new Dictionary<String, PythonDict>();
    }

    public PythonDict(String value) {
        this.str_ = value;
    }

    public bool isString() {
        return (this.str_ != null);
    }

    /* Private fields */
    Dictionary<String, PythonDict> dict_ = null;
    String str_ = null;
}
Run Code Online (Sandbox Code Playgroud)

这个类适用于无限级别,可以在没有显式转换的情况下读取(危险,也许,但是嘿).

用法如下:

        PythonDict s = new PythonDict();
        s["Hello"] = new PythonDict();
        s["Hello"]["32"] = "hey there";
        s["Hello"]["34"] = new PythonDict();
        s["Hello"]["34"]["Section"] = "Your face";
        String result = s["Hello"]["34"]["Section"];
        s["Hi there"] = "hey";
Run Code Online (Sandbox Code Playgroud)

非常感谢Jared Par!

Jar*_*Par 12

你可以通过拥有类来实现这一点,让我们称之为PythonDictionary,从中返回mydict["bc"]具有以下成员.

  • 允许["de"]访问的索引器属性
  • 从字符串到PythonDictionary的隐式转换

这应该允许两种情况编译得很好.

例如

public class PythonDictionary {
    public string this[string index] {
        get { ... }
        set { ... }
    }
    public static implicit operator PythonDictionary(string value) {
        ...
    }
}

public void Example() {
    Dictionary<string, PythonDictionary> map = new Dictionary<string, PythonDictionary>();
    map["42"]["de"] = "foo";
    map["42"] = "bar";
}
Run Code Online (Sandbox Code Playgroud)