[英]Fallback accessors in C#?
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#支持反射,但它是只读的(对于已加载的程序集)。 这意味着您不能更改任何方法,属性或任何其他元数据。 尽管您可以创建一个动态属性 ,但调用它并不是很方便-甚至比使用Get
方法还要糟糕。 除了为您的类使用Dictionary<string, object>
和一个索引器之外,您还可以做很多其他事情。 无论如何,如果您拥有那么多属性,做字典是否更好?
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
存在。
我不确定,但是4.0版的动态功能可能会帮助您。 不过,您必须等待...
我可以问:您为什么不想要各个属性? 这是表达与对象关联的数据的惯用.NET方法。
就个人而言,假设数据不是稀疏的,我将保留属性并让整体方法使用反射-这将使您的编译代码尽可能快:
protected T Get<T>(string name, T @default)
{
var prop = GetType().GetProperty(name);
if(prop == null) return @default;
return (T) prop.GetValue(this, null);
}
当然,如果您不关心定义的属性本身,那么可以使用索引器和查找(例如字典)。 您还可以使用postharp进行某些操作,以将一组属性转换为一个属性包-但是可能不值得。
如果您希望这些属性可用于数据绑定和运行时发现,但不能在编译时对其进行定义,那么您将需要查看动态类型描述符;否则,请参见图4。 ICustomTypeDescriptor
或TypeDescriptionProvider
相当多的工作,但用途广泛(如果需要更多信息,请告诉我)。
这与使用动态属性名称的Python不同,但是您可能会发现它很有用:
using System;
using System.Collections.Generic;
namespace Program
{
class Program
{
static void Main(string[] args)
{
MyList<int> list = new MyList<int>();
// Add a property with setter.
list["One"] = 1;
// Add a property with getter which takes default value.
int two = list["Two", 2];
Console.WriteLine("One={0}", list["One"]);
Console.WriteLine("Two={0} / {1}", two, list["Two"]);
try
{
Console.WriteLine("Three={0}", list["Three"]);
}
catch
{
Console.WriteLine("Three does not exist.");
}
}
class MyList<T>
{
Dictionary<string, T> dictionary = new Dictionary<string,T>();
internal T this[string property, T def]
{
get
{
T value;
if (!dictionary.TryGetValue(property, out value))
dictionary.Add(property, value = def);
return value;
}
}
internal T this[string property]
{
get
{
return dictionary[property];
}
set
{
dictionary[property] = value;
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.