How to compare a Microsoft.CodeAnalysis.ITypeSymbol to a System.Type

后端 未结 2 1973
野的像风
野的像风 2021-02-10 04:55

I have successfully received an ITypeSymbol from a SyntaxNode by using:

SemanticModel.GetTypeInfo(sytaxNode).ConvertedType

Now I would like to

相关标签:
2条回答
  • 2021-02-10 05:04

    Based on the answer from @Tamas, I created the following recursive solution that works for closed generic types.

        static bool TypeSymbolMatchesType(ITypeSymbol typeSymbol, Type type, SemanticModel semanticModel)
        {
            return GetTypeSymbolForType(type, semanticModel).Equals(typeSymbol);
        }
    
        static INamedTypeSymbol GetTypeSymbolForType(Type type, SemanticModel semanticModel)
        {
    
            if (!type.IsConstructedGenericType)
            {
                return semanticModel.Compilation.GetTypeByMetadataName(type.FullName);
            }
    
            // get all typeInfo's for the Type arguments 
            var typeArgumentsTypeInfos = type.GenericTypeArguments.Select(a => GetTypeSymbolForType(a, semanticModel));
    
            var openType = type.GetGenericTypeDefinition();
            var typeSymbol = semanticModel.Compilation.GetTypeByMetadataName(openType.FullName);
            return typeSymbol.Construct(typeArgumentsTypeInfos.ToArray<ITypeSymbol>());
        }
    
    0 讨论(0)
  • 2021-02-10 05:10

    You can get the INamedTypeSymbol for a type name with Compilation.GetTypeByMetadataName().

    So try this:

    semanticModel.GetTypeInfo(sytaxNode).ConvertedType.Equals(
      semanticModel.Compilation.GetTypeByMetadataName(typeof(WhateverType).FullName))
    

    This won't work with closed generic types, for those you'll need to do a bit more. For example:

    var ienumerableType = semanticModel.Compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1");
    var intType = semanticModel.Compilation.GetTypeByMetadataName("System.Int32");
    var type = ienumerableType.Construct(intType);
    
    0 讨论(0)
提交回复
热议问题