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”,因为在一个对象中可以有许多具有各种键类型的字典。显然,必须做一些不同的事情而不是上面的代码。我只是不知道该怎么做。谢谢

4

1 回答 1

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;
    }
于 2013-04-02T16:29:11.007 回答