考虑以下通用类
Dictionary<TKey, TValue>
List<T>
CustomHashMap<K, V>
有没有可能反映出赋予通用类型参数的名称?
例如
"TKey", "TValue"
"T"
"K", "V"
Dictionary<TKey, TValue>
List<T>
CustomHashMap<K, V>
有没有可能反映出赋予通用类型参数的名称?
例如
"TKey", "TValue"
"T"
"K", "V"
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 {}