我编写了一个迭代实例的泛型参数类型的方法......
Dictionary<string, Guid>
返回
TKey:System.String
TValue:System.Guid
Tuple<Guid, bool, StringBuilder>
返回
T1:System.Guid
T2:System.Boolean
T3:System.Text.StringBuilder
方式
public static Dictionary<String, Type> GetGenericParameters(Type type)
{
Dictionary<string, Type> result = new Dictionary<string, Type>();
Type[] tValues = type.GetGenericArguments();
Type[] tKeys = type.GetGenericTypeDefinition().GetGenericArguments();
if (tValues.Length == tKeys.Length)
{
for (int index = 0; index < tValues.Length; index++)
{
result.Add(tKeys[index].Name, tValues[index]);
}
}
return result;
}
测试
foreach (KeyValuePair<string, Type> pair in GetGenericParameters(typeof(Tuple<string, int, Guid, StringBuilder, long, bool, Tuple<bool, string>>)))
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
结果:
T1:System.String
T2:System.Int32
T3:System.Guid
T4:System.Text.StringBuilder
T5:System.Int64
T6:System.Boolean
T7:System.Tuple`2 [System.Boolean,System.String]
它似乎工作正常......但我的直觉是,有些情况会破坏这种逻辑,并且可能会被写成更高效...可能与linq或其他东西......任何想法如何改善这一点并确保它不会破裂?