我正在一個邏輯,我已經從詞典鍵/值對填充複合類實例。複合類將被標記爲屬性,這些屬性將映射到字典中的鍵。 一個特定的要求是,如果C1類具有C2類型的屬性,但字典中沒有對要映射C2類屬性的對,那麼C2應該設置爲null。否則,如果至少有一個可映射的C2屬性,則C1的C2屬性必須實例化。 我已經寫了一個遞歸函數來實現這個邏輯。該要求不按預期工作。我正在使用一個標誌isInstanceValuePresent,它檢查是否至少可以映射C2的屬性之一。否則,這是錯誤的價值應該告訴我,我必須爲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);
}
}
}
}
我甚至明白,如果有人可以幫助我優化功能。 – Lucifer
邏輯如何失敗?它沒有執行,或者結果不如預期的那樣? – Daniel