Last active
November 25, 2021 14:18
-
-
Save daiplusplus/44ad0b59e27f14e15061b332053c1c9e to your computer and use it in GitHub Desktop.
System.Type's properties comparison for different kinds of generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This LinqPad 6 script is for https://stackoverflow.com/a/70111165/159145 | |
<Query Kind="Program"> | |
<IncludePredicateBuilder>false</IncludePredicateBuilder> | |
<UseNoncollectibleLoadContext>true</UseNoncollectibleLoadContext> | |
</Query> | |
class NormalClass { } | |
class Generic<T> { } | |
class Derived : Generic<String> { } | |
class HasGenericMethod { public void Foo<T>() {} } | |
void Main() | |
{ | |
Type openGeneric = typeof(Generic<>); | |
Type genTypeArg = openGeneric.GetGenericArguments().Single(); | |
Type genMethodArg = typeof(HasGenericMethod).GetMethod( nameof(HasGenericMethod.Foo) )!.GetGenericArguments().Single(); | |
Type[] types = new Type[] | |
{ | |
typeof(NormalClass ), | |
openGeneric, | |
typeof(Generic<String>), | |
typeof(Derived ), | |
genTypeArg, | |
genMethodArg, | |
typeof(Generic<String>[]) | |
}; | |
var withMethodsResults = types | |
.Select( t => new | |
{ | |
_0_Type = t, | |
_1_IsTypeDefinition = t.IsTypeDefinition, | |
_2_IsGenericType = t.IsGenericType, | |
_3_ContainsGenericParameters = t.ContainsGenericParameters, | |
_4_GenericTypeArguments = t.GenericTypeArguments, | |
_5_IsConstructedGenericType = t.IsConstructedGenericType, | |
_6_IsGenericTypeDefinition = t.IsGenericTypeDefinition, | |
_7_IsGenericParameter = t.IsGenericParameter, | |
_8_IsGenericMethodParameter = t.IsGenericMethodParameter, | |
_9_IsGenericTypeParameter = t.IsGenericTypeParameter, | |
GetGenericArguments = TryDo( t, t2 => t2.GetGenericArguments() ), | |
GetGenericParameterConstraints = TryDo( t, t2 => t2.GetGenericParameterConstraints() ), | |
GetGenericTypeDefinition = TryDo( t, t2 => t2.GetGenericTypeDefinition() ) | |
} ) | |
.ToList(); | |
withMethodsResults.Dump( alpha: true ); | |
} | |
public static Object? TryDo<TSource,TResult>( TSource src, Func<TSource,TResult> getter )//, TResult defaultValue ) | |
{ | |
try | |
{ | |
TResult result = getter( src ); | |
return result; | |
} | |
catch( Exception ex ) | |
{ | |
return ex; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment