c# - Roslyn SemanticModel.GetTypeInfo(SyntaxNode node).Type 返回 null
问题描述
我有一段这样的代码:
using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace TestProject
{
class Program
{
private const string text = @"
using System;
class Program
{
static void Main(string[] args)
{
if (args == null) { }
if (args != null) { }
}
}";
static void Main(string[] args)
{
var tree = CSharpSyntaxTree.ParseText(text);
var compilation = CSharpCompilation.Create(null).AddSyntaxTrees(tree);
var semanticModel = compilation.GetSemanticModel(tree);
var root = tree.GetRoot();
foreach (var param in root.DescendantNodes().OfType<ParameterSyntax>().ToList())
{
var type = param.Type;
var name = param.Identifier;
var typeSymbol = semanticModel.GetTypeInfo(param).Type;
}
}
}
}
我的目标是能够检查一个类型是否是引用类型。我想这样做
typeSymbol.IsReferenceType
但问题是semanticModel.GetTypeInfo(param).Type
返回null
。在同一个param.Type
返回正确的值(string[]
)。
任何想法为什么它会以这种方式工作以及如何修复它?
解决方案
如果目标只是获取参数类型,那么您可以将示例更改为 call semanticModel.GetTypeInfo(type)
。
如果您想了解有关参数的所有信息(它是否具有属性、是不是ref
、是不是params
等...),那么您可能想要使用semanticModel.GetDeclaredSymbol(param)
.
推荐阅读
- java - 与 JPA Detach api 等效的 hsql/jdbc 是什么?它到底是做什么的?
- regex - 在 vscode 中使用正则表达式来更改一些代码
- android - 如何在库中包含另一个库
- java - 调用服务依赖于使用单个控制器的 PathVariable
- javascript - 嵌套函数调用在 express.js 中用 module.exports() 包装后不起作用
- javascript - 建立在选择列表中单击的项目数组并将值分配给元素
- spring - 接受 Hashmap 作为 POST 调用的主体
- javascript - ASP.NET Razor - 为使用 JQuery 的编辑器添加 min 属性
- kubernetes - 在 Seldon Core 上将模型 A 的输出路由为模型 B 的输入
- javascript - 如何访问两个参数,一个是数组,另一个是值?