我需要编写一个泛型类型为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"作为字典键的类型,因为在一个对象中可以有许多具有不同键类型的字典。显然,必须做一些不同的事情,而不是上面的代码。我只是不知道该怎么做。由于
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;
}