【发布时间】:2019-10-31 23:46:41
【问题描述】:
我无法使用 Roslyn 的语义模型检索字段的类型信息。它适用于 int 或 string 等简单类型的字段,但不适用于 Dictionary。
代码如下:
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace SemanticsCS
{
class Program
{
static void Main(string[] args)
{
var tree = CSharpSyntaxTree.ParseText(@"
public class MyClass {
int z;
Dictionary<string, string> dict;
int Method1() { int x = 3; return 0; }
void Method2()
{
int x = Method1();
}
}
}");
//
Dictionary<string, string> dict;
var Mscorlib = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);
//Looking at the first method symbol
foreach (var nodeSyntax in tree.GetRoot().DescendantNodes())
{
var methodSymbol = model.GetSymbolInfo(nodeSyntax);
var symbolInfo = model.GetSymbolInfo(nodeSyntax);
var typeInfo = model.GetTypeInfo(nodeSyntax);
if (typeInfo.Type != null)
Console.WriteLine(nodeSyntax.GetText() + ":" + typeInfo.Type.Kind);
}
}
}
}
当我运行它时,我得到了
int :NamedType
Dictionary<string, string> :ErrorType
string:NamedType
string:NamedType
int :NamedType
int :NamedType
3:NamedType
0:NamedType
void :NamedType
int :NamedType
Method1():NamedType
我想 ErrorType 是 Roslyn 在未检索到实际类型时使用的默认值。
Dictionary 的定义应该来自 mscorlib。会不会是找不到?或者,我是否需要更改代码中的某些内容?显然它正在我同事的一台计算机上运行,但不是在我的计算机上运行。是配置.Net使用的问题吗?
【问题讨论】:
-
你需要使用完整的类型名
System.Collections.Generic.Dictionary<string, string>或者ausing语句 -
@Kalten 可能是正确的。您还可以使用
compilation.GetDiagnostics()获取错误/警告,这样可以更轻松地找出问题所在。 -
感谢您的建议。我错过了用于测试的 VB 代码不包含 Imports 语句的事实,所以即使我有对 mscorlib 的引用,命名空间也是未知的。在我添加命名空间前缀后它工作了。