一個我喜歡的Python的事情就是這樣,你可以customize attribute access:C#相當於Python中的屬性定製/ JavaScript對象字面
class Foo(object):
def __getattr__(self, name):
if some_predicate(name):
# ...
else:
# Default behaviour
raise AttributeError
你可以更直接地與JavaScript的對象文字符號類似的東西。
我的問題是:你怎麼能在C#中實現類似的東西?重載'。'運營商將如何做這件事,但它不是在允許
那種事情的一個例子,我心目中是定義一個類,如:
public class MyClass
{
public IDictionary Properties {get; private set;}
public MyClass(IDictionary properties)
{
this.Properties = properties;
}
// Overload the '.' operator - not allowed!
public static object operator .(MyClass inst, string name)
{
return inst.Properties[name];
}
}
使用類像這樣的:
class Program
{
static void Main(string[] args)
{
IDictionary properties = new Dictionary<string, string>() {
{ "prop1", "value1"}, { "prop2", "value2"} };
var my = new MyClass(properties);
System.Console.WriteLine(my.prop1); // Doesn't work!
}
}
(注:我問了一下C++ here了類似的問題,原來同樣的問題,而是分裂,使每種語言更具體)
非常好 - 這正是我一直在尋找的。非常感謝。 – 2014-11-02 11:01:23
添加了我的示例使用DynamicObject進行記錄的答案。 – 2014-11-02 11:08:59