查找对象的属性,该对象是其键具有特定类型的字典

时间:2013-04-02 16:05:25

标签: c# .net reflection

我需要编写一个泛型类型为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'作为字典键的类型,因为在一个对象中可能有许多具有各种键类型的字典。显然,必须要做一些不同的事情,而不是上面的代码。我只是无法弄清楚如何做到这一点。谢谢

1 个答案:

答案 0 :(得分: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;
    }