How to reflect generic type parameters in C # .NET

Consider the following general classes

Dictionary<TKey, TValue> List<T> CustomHashMap<K, V> 

Is it possible to reflect the names assigned to parameters of a general type?

Example

 "TKey", "TValue" "T" "K", "V" 
+4
source share
1 answer

This seems like a trick:

 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 {} 
+4
source

Source: https://habr.com/ru/post/1443760/


All Articles