Starting with a TypeInfo
object that represents a generic type, I want to retrieve TypeInfo
s for each type parameter of the generic type. I would like to expose this as an extension method with this signature:
public static TypeInfo[] GetTypeParameterInfos(this TypeInfo genericType) {
//Do stuff
}
If I pass in a TypeInfo
representing List<int>
, it should return an array that contains 1 TypeInfo
representing int
. If I pass in a TypeInfo
represnting Dictionary<int, string>
, it should return an array with an int
and a string
TypeInfo
.
Is this possible? How?
Update/Solution:
To clarify, I was asking about Microsoft.CodeAnalysis.TypeInfo
, not System.Reflection.TypeInfo
. This name confusion has been a real problem in getting meaningful Google results. However, it looks like what I really want is Microsoft.CodeAnalysis.ITypeSymbol
, which can be easily acquired from a Roslyn TypeInfo
with the TypeInfo.Type
property.
The solution is in the INamedTypeSymbol.TypeArguments
property, which returns an ImmutableArray<ITypeSymbol>
corresponding to the type arguments of the given type symbol.
TypeInfo myGenericType = GetTypeInfoSomehow();
ImmutableArray<ITypeSymbol> typeArguments = myGenericType.Type.TypeArguments;
As you can see from the source, Roslyn's TypeInfo
is a very thin wrapper around ITypeSymbol
; that is where you need to look to get anything useful about the type.
If the type is in fact a generic type (as opposed to special types like arrays or pointers), it will actually be an INamedTypeSymbol, which has all the APIs necessary to investigate the type.
In your case, you just want its TypeArguments
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With