如何在C#.NET中反映泛型类型参数

4
考虑以下通用类
Dictionary<TKey, TValue>

List<T>

CustomHashMap<K, V>

有没有可能反映出赋予通用类型参数的名称?

例如

"TKey", "TValue"

"T"

"K", "V"
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 {}

投票++; // 运行得很好! :-) - Matthew Layton
1
@activwerx 更改了代码,提供了一个很好的实用函数,可适用于通用类型定义和实例化。 - millimoose

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接