C# 有类似 Python 的东西__getattr__
吗?
我有一个具有许多属性的类,它们都共享相同的访问器代码。我希望能够完全删除单个访问器,就像在 Python 中一样。
这是我的代码现在的样子:
class Foo
{
protected bool Get(string name, bool def)
{
try {
return client.Get(name);
} catch {
return def;
}
}
public bool Bar
{
get { return Get("bar", true); }
set { client.Set("bar", value); }
}
public bool Baz
{
get { return Get("baz", false); }
set { client.Set("baz", value); }
}
}
这就是我想要的:
class Foo
{
public bool Get(string name)
{
try {
return client.Get(name);
} catch {
// Look-up default value in hash table and return it
}
}
public void Set(string name, object value)
{
client.Set(name, value)
}
}
有没有办法在 C# 中实现这一点而无需Get
直接调用?
谢谢,