【发布时间】:2010-11-25 18:22:19
【问题描述】:
在 C# 中是否有模仿以下 python 语法的好方法:
mydict = {}
mydict["bc"] = {}
mydict["bc"]["de"] = "123"; # <-- This line
mydict["te"] = "5"; # <-- While also allowing this line
换句话说,我想要一些具有 [] 样式访问权限的东西,它可以返回另一个字典或字符串类型,具体取决于它的设置方式。
我一直在尝试使用自定义类解决此问题,但似乎无法成功。有什么想法吗?
谢谢!
编辑:我很邪恶,我知道。 Jared Par 的解决方案很棒。 . .对于这种形式的 2 级字典。但是,我也对进一步的级别感到好奇。 . .例如,
mydict["bc"]["df"]["ic"] = "32";
等等。有什么想法吗?
编辑 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;
}
此类适用于无限关卡,无需显式转换即可读取(可能很危险,但是嘿)。
这样使用:
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";
非常感谢 Jared Par!
【问题讨论】:
标签: c# python syntax dictionary types