我有一个类(Customer),它拥有超过200个字符串变量作为属性。我使用带有key和value参数的方法。我尝试从xml文件中提供键和值。为此,value必须替换为Customer类的属性(字符串变量)。
即
Customer
{
public string Name{return _name};
public string Address{return _address};
}
CallInput
{
StringTempelate tempelate = new StringTempelate();
foreach(item in items)
tempelate .SetAttribure(item.key, item.Value --> //Say this value is Name, so it has to substitute Customer.Name
}
有可能吗?
发布于 2009-08-18 12:42:17
您可以使用反射来“按名称”设置属性。
using System.Reflection;
...
myCustomer.GetType().GetProperty(item.Key).SetValue(myCustomer, item.Value, null);
您还可以使用GetValue读取属性,或者使用GetType().GetProperties()获取所有属性名称的列表,该方法返回一个PropertyInfo数组( Name属性包含属性名称)
发布于 2009-08-18 12:56:41
反射是一个选项,但是200个属性是...很多。碰巧的是,我目前正在做类似的事情,但是类是由code-gen创建的。为了适应“按名称”的用法,我添加了一个索引器(在代码生成阶段):
public object this[string propertyName] {
get {
switch(propertyName) {
/* these are dynamic based on the the feed */
case "Name": return Name;
case "DateOfBirth": return DateOfBirth;
... etc ...
/* fixed default */
default: throw new ArgumentException("propertyName");
}
}
}
这提供了“按名称”的便利性,但具有良好的性能。
发布于 2009-08-18 12:45:45
使用反射和字典对象作为items集合。
Dictionary<string,string> customerProps = new Dictionary<string,string>();
Customer myCustomer = new Customer(); //Or however you're getting a customer object
foreach (PropertyInfo p in typeof(Customer).GetProperties())
{
customerProps.Add(p.Name, p.GetValue(customer, null));
}
https://stackoverflow.com/questions/1293549
复制相似问题