首页 > 解决方案 > 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[])。

任何想法为什么它会以这种方式工作以及如何修复它?

标签: c#.netroslynroslyn-code-analysis

解决方案


如果目标只是获取参数类型,那么您可以将示例更改为 call semanticModel.GetTypeInfo(type)

如果您想了解有关参数的所有信息(它是否具有属性、是不是ref、是不是params等...),那么您可能想要使用semanticModel.GetDeclaredSymbol(param).


推荐阅读