【发布时间】:2014-01-09 10:24:55
【问题描述】:
我正在研究从字典键/值对填充复合类实例的逻辑。复合类将用属性标记,这些属性将映射到字典中的键。 一个具体要求是,如果类 C1 具有类 C2 类型的属性,但字典中没有要映射的类 C2 的属性对,则 C2 应设置为 null。否则,如果 C2 至少有一个属性可以映射,则必须实例化 C1 的 C2 属性。 我写了一个递归函数来实现这个逻辑。该要求未按预期工作。我正在使用一个标志 isInstanceValuePresent 来检查是否可以映射 C2 的至少一个属性。否则,它的错误值应该告诉我必须将 null 分配给类 C1 的 C2 属性。如果有人可以帮助我理解逻辑失败的原因以及正确的解决方案是什么,我将非常感激。下面是静态递归方法:
/// <summary>
/// Populates the given instance object with the supplied source dictionary values
/// </summary>
/// <param name="modelInstance">The object whose properties are to be initialized with the data</param>
/// <param name="source">The source dictionary containing Schema(Keys) and corresponding Values</param>
private static void PopulateModelInstance(object modelInstance, IDictionary<string, string> source)
{
bool isInstanceValuePresent = false;
foreach (PropertyInfo propInfo in modelInstance.GetType().GetProperties())
{
//Identify Custom attribute
DataMappingKeyAttribute attribute = (DataMappingKeyAttribute)Attribute.GetCustomAttribute(propInfo, typeof(DataMappingKeyAttribute));
if (attribute != null && !string.IsNullOrEmpty(attribute.MappingKey))
{
if (propInfo.PropertyType.IsPrimitive || propInfo.PropertyType.Equals(typeof(string)))
{
string sourceKey = attribute.MappingKey;
if (source.ContainsKey(sourceKey))
{
isInstanceValuePresent = true;
// Get propInfo attribute value from Dictionary
//var propertySourceValue = source[(propInfo.PropertyType.GetCustomAttribute(typeof(DataMappingKeyAttribute)) as DataMappingKeyAttribute).MappingKey];
string sourceValue = source[attribute.MappingKey];
// Set propInfo value on the model instance
if (CanChangeType(sourceValue, propInfo.PropertyType) && propInfo.CanWrite && (!propInfo.PropertyType.IsClass || propInfo.PropertyType.Equals(typeof(string))))
propInfo.SetValue(modelInstance, Convert.ChangeType(sourceValue, propInfo.PropertyType), null);
}
}
}
if (propInfo.PropertyType.IsClass && !propInfo.PropertyType.Equals(typeof(string)) && propInfo.CanWrite)
{
isInstanceValuePresent = false;
object referenceTypeInstance = Activator.CreateInstance(propInfo.PropertyType);
PopulateModelInstance(referenceTypeInstance, source);
if (isInstanceValuePresent == false)
{
propInfo.SetValue(modelInstance, null, null);
referenceTypeInstance = null;
}
else
{
propInfo.SetValue(modelInstance, referenceTypeInstance, null);
}
}
}
}
【问题讨论】:
-
如果有人能帮我优化功能,我什至感激不尽。
-
逻辑如何失败?它没有执行,或者您的结果如何不符合预期?
标签: c# reflection recursion static