如果我有一个拥有FirstName的属性的类Perso,我能通过如下方式访问:
Person.FirstName = "Mike";
能通过下面的方式来访问吗
Person["FirstName"]="Mike";
通过反射类来实现,但是这种方法性能比较低。
publci class YourClass
...{
//...
public object this[string name]
...{
get
...{
PropertyInfo info = this.PropertyInfoByName(name);
return info.GetValue(this,null);
}
set
...{
PropertyInfo info = this.PropertyInfoByName(name);
info.SetValue(this,value,null);
}
}
private PropertyInfo PropertyInfoByName(string name)
...{
Type type = this.GetType();
PropertyInfo info = type.GetProperty(name);
if (info == null)
...{
throw new Exception(String.Format("对象{0}的属性{1}不能被访问 .", type.FullName, name));
}
return info;
}
//...
}
本文介绍了一种在 C# 中使用动态属性访问的方法,通过实现索引器和反射来间接读写类的属性值,尽管这种方法可能带来性能上的开销。
957

被折叠的 条评论
为什么被折叠?



