【发布时间】:2015-11-14 10:51:57
【问题描述】:
我有几个以与下面类似的方式定义的数据类,我正在尝试决定是为每个数据类提供一个内置构造函数来填充成员,还是在调用方法中只使用一次反射:
public class reportData
{
public List<Deposits> Deposits;
}
public class Deposits
{
public Deposits(List<Dictionary<string, string>> LPQReq)
{
PropertyInfo[] properties = typeof(Deposits).GetProperties();
foreach (Dictionary<string, string> PQList in LPQReq)
{
foreach (KeyValuePair<string, string> kvp in PQList)
{
MemberInfo info = typeof(Deposits).GetField(kvp.Key) as MemberInfo ?? typeof(Deposits).GetProperty(kvp.Key) as MemberInfo;
//PropertyInfo property = properties[kvp.Key];
// info.setvalue
}
}
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(typeof(Deposits), null));
}
}
public string YPBRNO { get; set; }
public string YPBNA { get; set; }
public string YPTME { get; set; }
... cut for brevity
我想使用反射让我的构造函数获取字典键值对列表,并且键与属性名称匹配...
然后我可以使用类似的东西
PropertyInfo property = properties[kvp.Key];
或
info.setValue(typeof(Deposits), value, null);
当然,一种方法是遍历我的类型中的所有属性,并在调用setValue() 之前检查property.name=kvp.key 是否像这样:
foreach (Dictionary<string, string> PQList in LPQReq)
{
foreach (KeyValuePair<string, string> kvp in PQList)
{
MemberInfo info = typeof(Deposits).GetField(kvp.Key) as MemberInfo ?? typeof(Deposits).GetProperty(kvp.Key) as MemberInfo;
//PropertyInfo property = properties[kvp.Key];
// info.setvalue
foreach (PropertyInfo property in properties)
{
if (property.Name==kvp.Key)
{
property.SetValue(typeof(Deposits), kvp.Value, null);
}
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(typeof(Deposits), null));
}
}
}
所以现在我已经做到了,这样做是不是一个好主意,在每个类的构造函数中(然后我必须在外部调用)
或者我应该在调用方法中使用反射来设置所有属性,而不必知道属性是什么......就像这样(这发生在一个循环中):
Type target = Type.GetType(DocumentType);
foreach (Dictionary<string, string> PQList in LPQReq)
{
foreach (KeyValuePair<string, string> kvp in PQList)
{
PropertyInfo prop = target.GetProperty(kvp.Key);
prop.SetValue (target, kvp.Value, null);
}
Console.WriteLine("Template Name = {0}", templateName);
}
编辑:
只是想提一下,我确实阅读了SO 1044455: c-sharp-reflection-how-to-get-class-reference-from-string,以了解如何仅从名称返回数据类...
所以我最初以为我会在我的数据类之外使用反射,但遇到了一些障碍!
【问题讨论】:
-
如果您不考虑性能,我只会继续这样做。
-
@Aron:是的,Reflection 相当慢,但这意味着我可以编写一种方法来填充十几个或更多数据类(这将是 VS 2013 报告的数据源)......和无论如何,对于这项服务,它可能是每小时 2 打交易的情况......所以在不到一秒的时间内测量的性能应该不会受到影响,因为目前我们正在使用 MS Word 打印报告,而且速度非常慢(至少 7 秒每个事务)由于 Word 互操作开销。
标签: c# reflection properties member