通过字符串名称设置/获取类属性

我要做的是使用字符串设置类中属性的值。例如,我的类具有以下属性:

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

所有字段都是 string类型的,所以我提前知道它总是一个字符串。现在,我希望能够像使用 DataSet对象那样使用字符串设置属性。就像这样:

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

理想情况下,我只需要分配一个变量,然后使用变量中的字符串名称设置属性:

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

我读过关于反射的文章,也许这就是实现它的方法,但我不知道如何在保持类中属性访问完整的情况下设置它。我想仍然能够使用:

myClass.Name = "John"

任何代码示例都非常棒。

110013 次浏览

You can add indexer property, a pseudocode:

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);
}
}
}

May be something like this?

    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>();
}
}

You can add an indexer to your class and use reflection to aces the properties:

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;
}
}
}