【发布时间】:2012-03-14 00:44:40
【问题描述】:
我正在编写自己的方法来将对象图转换为自定义对象,因为 JavaScriptSerializer 会在 null 值上触发错误。
这就是我目前所拥有的:
internal static T ParseObjectGraph<T>(Dictionary<string, object> oGraph)
{
T generic = (T)Activator.CreateInstance<T>();
Type resType = typeof(T);
foreach (PropertyInfo pi in resType.GetProperties())
{
object outObj = new object();
if (oGraph.TryGetValue(pi.Name.ToLower(), out outObj))
{
Type outType = outObj.GetType();
if (outType == pi.PropertyType)
{
pi.SetValue(generic, outObj, null);
}
}
}
return generic;
}
现在pi.SetValue() 方法运行,并没有引发错误,但是当我查看generic 的属性时,它仍然和之前一样。
它经过的第一个属性是一个布尔值,所以值最终是这样的
generic = an object of type MyCustomType
generic.property = false
outObj = true
pi = boolean property
outType = boolean
那么SetValue方法运行后,generic.property仍然设置为false。
【问题讨论】:
-
不相关但
generic.GetType()在我的基准测试中会比typeof(T)有更好的性能。也没有理由强制转换Activator.CreateInstance<T>的结果,它已经返回了T的实例。 -
谢谢你,我会改变那些东西。我也偶然找到了答案。
-
你需要调试这个。 if (outType == pi.PropertyType) 没有意义,不知道你在做什么。
-
@HansPassant 检查它们是否是同一类型。
标签: c# generics reflection