如何将Microsoft.CodeAnalysis.ITypeSymbol比作System.Type的 [英] How to compare a Microsoft.CodeAnalysis.ITypeSymbol to a System.Type

查看:323
本文介绍了如何将Microsoft.CodeAnalysis.ITypeSymbol比作System.Type的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功收到ITypeSymbol从SyntaxNode使用:

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

SemanticModel.GetTypeInfo(sytaxNode).ConvertedType

现在我想知道,如果这 ITypeSymbol 对应一个的System.Type 实例,它是存在于我的执行代码,如的typeof(IEnumerable的< INT>) someObject.GetType()

Now I would like to know if this ITypeSymbol corresponds to a System.Type instance that is present in my executing code, like typeof(IEnumerable<int>) or someObject.GetType().

我试过

typeInfo.ConvertedType.ToString() == type.ToString()

但这些不使用相同的格式规则,比如像<仿制药code>的IEnumerable< INT>

But these do not use the same formatting rules, for instance for generics like IEnumerable<int>

TypeInfo.ToString()==System.Collections.Generic .IEnumerable< INT>中

,而

typeof(IEnumerable<int>).ToString() == "System.Collections.Generic.IEnumerable`1[System.Int32]"

此外,我认为这将是更好,在短短的命名空间和类型名称代替比较AssemblyQualifiedNames以避免可能的名称冲突。

Moreover I think it would be better to compare AssemblyQualifiedNames in stead of just the Namespace and type name to avoid possible name clashes.

理想情况下,我想能够得到实际的System.Type实例对应于的ITypeInfo我从语义模型得到了我的执行代码(前提是必需的程序集加载和/或可用)。这将使检查,如果该类型是从其他类型等分配。

Ideally I would like to be able to get the actual System.Type instance in my executing code that corresponds to the ITypeInfo I got from the semantic model (provided that the required assembly is loaded and/or available). That would allow checking if the type is assignable from some other type etc.

推荐答案

您可以在 INamedTypeSymbol 类型名称Compilation.GetTypeByMetadataName()

所以,试试这个

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);

这篇关于如何将Microsoft.CodeAnalysis.ITypeSymbol比作System.Type的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆