[英]In C#, is a dictionary whose keys are of type Type slower than a dictionary whose keys are of type ulong?
[英]Find properties of an object that are dictionary whose keys are of certain type
我需要編寫一個泛型類型為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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.