在自定义对象中添加以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class MyClass { public string MyName { get; set; } /// <summary> /// 使用字符串属性直接访问 /// </summary> /// <param name="propertyName"></param> /// <returns></returns> public object this[string propertyName] { get { // probably faster without reflection: // like: return Properties.Settings.Default.PropertyValues[propertyName] // instead of the following Type myType = this.GetType(); PropertyInfo myPropInfo = myType.GetProperty(propertyName); return myPropInfo.GetValue(this, null); } set { Type myType = this.GetType(); PropertyInfo myPropInfo = myType.GetProperty(propertyName); myPropInfo.SetValue(this, value, null); } } } |
使用:
1 2 3 |
MyClass obj = new MyClass(); var x = obj["MyName"]; obj["MyName"] = "hello"; |