我在 C# 中有一个对通用字典进行操作的函数:
public static string DoStuff<TKey, TValue>(Dictionary<TKey, TValue> dictionary)
{
// ... stuff happens here
}
我还有一个循环对象的函数。如果其中一个对象是 Dictionary<>,我需要将它传递给那个通用函数。但是,在编译时我不知道键或值的类型是什么:
foreach (object o in Values)
{
if (/*o is Dictionary<??,??>*/)
{
var dictionary = /* cast o to some sort of Dictionary<> */;
DoStuff(dictionary);
}
}
我该怎么做?
最佳答案
假设您不能在 Values
集合的类型中使您的方法通用,您可以使用动态:
foreach (object o in values)
{
Type t = o.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
string str = DoStuff((dynamic)o);
Console.WriteLine(str);
}
}
或者你可以使用反射:
foreach (object o in values)
{
Type t = o.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
var typeParams = t.GetGenericArguments();
var method = typeof(ContainingType).GetMethod("DoStuff").MakeGenericMethod(typeParams);
string str = (string)method.Invoke(null, new[] { o });
}
}
关于c# - 将对象转换为 Dictionary<TKey, TValue>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13654258/