问题
I am trying to get type info from ObjectCreationExpressionSyntax object but failed.
Here is example that reproduce the problem (see "ti.Type is null" in code):
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
namespace RoslynExample
{
class Program
{
static void Main(string[] args)
{
string solutionPath = @"..\..\..\RoslynExample.sln";
MSBuildWorkspace workspace = MSBuildWorkspace.Create();
Solution solution = workspace.OpenSolutionAsync(solutionPath).Result;
foreach (var project in solution.Projects)
{
if (project.Name == "RoslynBugProject")
{
foreach (var document in project.Documents)
{
var compilationUnit = document.GetSyntaxRootAsync().Result;
var semanticModel = document.GetSemanticModelAsync().Result;
new MyWalker(semanticModel).Visit(compilationUnit);
}
}
}
}
}
partial class MyWalker : CSharpSyntaxWalker
{
private SemanticModel _semanticModel;
public MyWalker(SemanticModel semanticModel)
{
_semanticModel = semanticModel;
}
public override void VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
var ti = _semanticModel.GetTypeInfo(node.Type); **<--- ti.Type is null**
base.VisitObjectCreationExpression(node);
}
}
}
"RoslynBugProject" project:
namespace RoslynBugProject
{
internal class Query
{
}
class Program
{
static void Main(string[] args)
{
var query = new Query();
}
}
}
How to get type info? Previous version of Roslyn returns not null value.
回答1:
You can install the Roslyn Syntax Visualizer, which will show you the syntax tree and also let you explore the SemanticModel APIs as well.
With that installed, you can try right-clicking on nodes and asking for the type symbol:

In this case, you'll discover a couple things:
- If using "View TypeSymbol (if any)", you can get the symbol from the
ObjectCreationExpression
itself, but not from any of its children (the "IdentifierName" or the "ArgumentList"), so this could be fixed by passingnode
toGetTypeInfo
instead ofnode.Type
. - If using "View Symbol (if any)", you can get the symbol from the "IdentifierName" but not from the
ObjectCreationExpression
, so you could also fix your code by passingnode.Type
toGetSymbolInfo
instead ofGetTypeInfo
.
来源:https://stackoverflow.com/questions/27535382/semanticmodel-gettypeinfo-for-objectcreationexpressionsyntax-type-returns-null