2013-04-02 84 views
0

我需要編寫一個擴展方法,它具有通用類型T,它貫穿對象的所有屬性,並對那些值爲類型t的字典執行某些操作:查找字典對象的屬性,該對象的鍵是特定類型的

public static T DoDictionaries<T,t>(T source, Func<t,t> cleanUpper) 
{ 

Type objectType = typeof(T); 
List<PropertyInfo> properties = objectType.GetProperties().ToList(); 
properties.Each(prop=> 
     { 
     if (typeof(Dictionary<????, t>).IsAssignableFrom(prop.PropertyType)) 
      { 
       Dictionary<????, t> newDictionary = dictionary 
        .ToDictionary(kvp => kvp.Key, kvp => cleanUpper(dictionary[kvp.Key])); 
       prop.SetValue(source, newDictionary); 
      } 
     }); 
return source; 
} 

我不能使用另一通用類型``K「」的類型字典鍵的,因爲可以有與各種密鑰類型許多字典中一個對象。顯然,需要完成不同的代碼而不是上面的代碼。我無法弄清楚如何做到這一點。謝謝

回答

2
public static TSource DoDictionaries<TSource, TValue>(TSource source, Func<TValue, TValue> cleanUpper) 
    { 
     Type type = typeof(TSource); 

     PropertyInfo[] propertyInfos = type 
      .GetProperties() 
      .Where(info => info.PropertyType.IsGenericType && 
          info.PropertyType.GetGenericTypeDefinition() == typeof (Dictionary<,>) && 
          info.PropertyType.GetGenericArguments()[1] == typeof (TValue)) 
      .ToArray(); 

     foreach (var propertyInfo in propertyInfos) 
     { 
      var dict = (IDictionary)propertyInfo.GetValue(source, null); 
      var newDict = (IDictionary)Activator.CreateInstance(propertyInfo.PropertyType); 
      foreach (var key in dict.Keys) 
      { 
       newDict[key] = cleanUpper((TValue)dict[key]); 
      } 
      propertyInfo.SetValue(source, newDict, null); 
     } 

     return source; 
    } 
相關問題