4

考虑以下泛型类

Dictionary<TKey, TValue>

List<T>

CustomHashMap<K, V>

是否可以反映给泛型类型参数的名称?

例如

"TKey", "TValue"

"T"

"K", "V"
4

1 回答 1

4

这似乎可以解决问题:

class Program
{
    static IEnumerable<string> GetGenericArgumentNames(Type type)
    {
        if (!type.IsGenericTypeDefinition)
        {
            type = type.GetGenericTypeDefinition();
        }

        foreach (var typeArg in type.GetGenericArguments())
        {
            yield return typeArg.Name;
        }
    }

    static void Main(string[] args)
    {
        // For a raw type
        Trace.WriteLine(string.Join(" ", GetGenericArgumentNames(typeof(Foo<>))));
        Trace.WriteLine(string.Join(" ", GetGenericArgumentNames(typeof(Foo<Quux>))));
    }

}

class Foo<TBar> {}

class Quux {}
于 2012-11-03T00:53:01.790 回答