我有一些类,并希望使用索引或类似的东西访问他们的属性
ClassObject[0] 或者更好 ClassObject["PropName"]
而不是这个
ClassObj.PropName.
谢谢
你需要索引器:
http://msdn.microsoft.com/en-us/library/aa288465(v=vs.71).aspx
public class MyClass
{
private Dictionary<string, object> _innerDictionary = new Dictionary<string, object>();
public object this[string key]
{
get { return _innerDictionary[key]; }
set { _innerDictionary[key] = value; }
}
}
// Usage
MyClass c = new MyClass();
c["Something"] = new object();
Run Code Online (Sandbox Code Playgroud)
这是记事本编码,所以请用一点盐,但索引器语法是正确的.
如果要使用它以便可以动态访问属性,那么索引器可以使用Reflection将键名作为属性名称.
或者,查看dynamic对象,特别是ExpandoObject可以转换为对象,IDictionary以便根据文字字符串名称访问成员.
你可以这样做,伪代码:
public class MyClass
{
public object this[string PropertyName]
{
get
{
Type myType = typeof(MyClass);
System.Reflection.PropertyInfo pi = myType.GetProperty(PropertyName);
return pi.GetValue(this, null); //not indexed property!
}
set
{
Type myType = typeof(MyClass);
System.Reflection.PropertyInfo pi = myType.GetProperty(PropertyName);
pi.SetValue(this, value, null); //not indexed property!
}
}
}
Run Code Online (Sandbox Code Playgroud)
在使用之后就像
MyClass cl = new MyClass();
cl["MyClassProperty"] = "cool";
Run Code Online (Sandbox Code Playgroud)
请注意,这不是完整的解决方案,因为如果您想要非公共属性/字段,静态属性等,则需要在反射访问期间"播放"BindingFlags.