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
?
谢谢,
最佳答案
没有。尽管 C# 支持反射,但它是只读的(对于加载的程序集)。这意味着您不能更改任何方法、属性或任何其他元数据。虽然你可以 create a dynamic property , 调用它不会很方便 - 它会比使用你的 Get
更糟糕方法。除了使用 Dictionary<string, object>
和您类(class)的索引器,您无能为力。不管怎样,如果你有那么多属性,做一本字典不是更好吗?
Python 不会在“编译时”(或至少在加载时)检查某个属性是否存在。 C# 可以。这是两种语言之间的根本区别。在 Python 中你可以这样做:
class my_class:
pass
my_instance = my_class()
my_instance.my_attr = 1
print(my_instance.my_attr)
在 C# 中,您将无法这样做,因为 C# 实际上会检查名称 my_attr
是否存在。存在于编译时。
关于c# - C# 中的回退访问器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/500096/