我有类(Customer),它包含200多个字符串变量作为属性.我正在使用带有键和值参数的方法.我试图从xml文件提供密钥和值.为此,必须使用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
}
Run Code Online (Sandbox Code Playgroud)
可能吗?
Dav*_*vid 23
您可以使用反射来"按名称"设置属性.
using System.Reflection;
...
myCustomer.GetType().GetProperty(item.Key).SetValue(myCustomer, item.Value, null);
Run Code Online (Sandbox Code Playgroud)
您还可以使用GetValue读取属性,或使用GetType()获取所有属性名称的列表.GetProperties()返回PropertyInfo数组(Name属性包含属性名称)
Jon*_*eet 13
好吧,你可以Type.GetProperty(name)
用来获得PropertyInfo
,然后打电话GetValue
.
例如:
// There may already be a field for this somewhere in the framework...
private static readonly object[] EmptyArray = new object[0];
...
PropertyInfo prop = typeof(Customer).GetProperty(item.key);
if (prop == null)
{
// Eek! Throw an exception or whatever...
// You might also want to check the property type
// and that it's readable
}
string value = (string) prop.GetValue(customer, EmptyArray);
template.SetTemplateAttribute(item.key, value);
Run Code Online (Sandbox Code Playgroud)
请注意,如果你这样做了很多,你可能想要的属性转换成Func<Customer, string>
委托实例-这将是多快,但比较复杂.有关详细信息,请参阅我的博文,了解如何通过反射创建代理
反思是一种选择,但200个属性......很多.碰巧的是,我现在正在研究这样的事情,但这些类是由代码生成的.为了适应"按名称"使用,我添加了一个索引器(在代码生成阶段):
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这给了"名字"的便利,但性能很好.
归档时间: |
|
查看次数: |
44749 次 |
最近记录: |