C#通过string名称设置/获取类属性

我想要做的是使用string在类中设置属性的值。 例如,我的课程具有以下属性:

myClass.Name myClass.Address myClass.PhoneNumber myClass.FaxNumber 

所有的字段都是stringtypes,所以我提前知道它总是一个string。 现在我想能够像使用DataSet对象一样使用string来设置属性。 像这样的东西:

 myClass["Name"] = "John" myClass["Address"] = "1112 River St., Boulder, CO" 

理想情况下,我只想分配一个variables,然后使用该variables的string名称来设置属性

 string propName = "Name" myClass[propName] = "John" 

我正在阅读反思,也许是这样做的方式,但我不知道如何去设置,同时保持在课堂上完整的财产访问。 我想仍然可以使用

 myClass.Name = "John" 

任何代码示例都会非常棒。

您可以添加索引器属性,一个伪代码

 public class MyClass { public object this[string propertyName] { get{ // probably faster without reflection: // like: return Properties.Settings.Default.PropertyValues[propertyName] // instead of the following Type myType = typeof(MyClass); PropertyInfo myPropInfo = myType.GetProperty(propertyName); return myPropInfo.GetValue(this, null); } set{ Type myType = typeof(MyClass); PropertyInfo myPropInfo = myType.GetProperty(propertyName); myPropInfo.SetValue(this, value, null); } } } 

添加到任何Class

 public class Foo { public object this[string propertyName] { get { return this.GetType().GetProperty(propertyName).GetValue(this, null); } set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); } } public string Bar { get; set; } } 

那么,你可以使用:

 Foo f = new Foo(); // Set f["Bar"] = "asdf"; // Get string s = (string)f["Bar"]; 

源: 使用C#中的reflection从string获取属性值

您可以添加一个索引器到你的类,并使用reflection来使属性:

 using System.Reflection; public class MyClass { public object this[string name] { get { var properties = typeof(MyClass) .GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { if (property.Name == name && property.CanRead) return property.GetValue(this, null); } throw new ArgumentException("Can't find property"); } set { return; } } } 

可能是这样的?

  public class PropertyExample { private readonly Dictionary<string, string> _properties; public string FirstName { get { return _properties["FirstName"]; } set { _properties["FirstName"] = value; } } public string LastName { get { return _properties["LastName"]; } set { _properties["LastName"] = value; } } public string this[string propertyName] { get { return _properties[propertyName]; } set { _properties[propertyName] = value; } } public PropertyExample() { _properties = new Dictionary<string, string>(); } }