简体   繁体   中英

How to get the semantic model from source in Roslyn

In all examples when using Roslyn , you have something like this:

SyntaxTree tree = CSharpSyntaxTree.ParseText(
@"using System;
using System.Collections.Generic;
using System.Text;

namespace HelloWorld
{
    // A whole program here...
}");

var root = (CompilationUnitSyntax)tree.GetRoot();

// Getting the semantic model (for MSCORELIB)
var compilation = CSharpCompilation.Create("HelloWorld")
                  .AddReferences(
                     MetadataReference.CreateFromFile(
                       typeof(object).Assembly.Location))
                  .AddSyntaxTrees(tree);
var model = compilation.GetSemanticModel(tree);

How to get the semantic model for my code?

The last piece of code retrieves the semantic model for mscorelib types: MetadataReference.CreateFromFile(typeof(object).Assembly.Location) so that I can inspect using s or other parts of the source and get symbol information.

But if I define types in HelloWorld and wanted to retrieve symbol info from those, I would the semantic model. But since I just loaded mscorelib I would not get this info.

How to load the semantic model for the source I just defined?

static void Main(string[] args)
{
    SyntaxTree tree = CSharpSyntaxTree.ParseText(
        @"using System;

        namespace HelloWorld
        {
            public class MyType{public void MyMethod(){}}
        }"
    );

    var root = (CompilationUnitSyntax)tree.GetRoot();
    var compilation = CSharpCompilation.Create("HelloWorld")
                      .AddReferences(
                         MetadataReference.CreateFromFile(
                           typeof(object).Assembly.Location))
                      .AddSyntaxTrees(tree);
    var model = compilation.GetSemanticModel(tree);
    var myTypeSyntax = root.DescendantNodes().OfType<TypeDeclarationSyntax>().First();
    var myTypeInfo = model.GetDeclaredSymbol(myTypeSyntax);
    Console.WriteLine(myTypeInfo);
}

Is this what you need? myTypeInfo is a type I defined in HelloWorld and I can get is info.

Just to explain, semantic model is something you can get from compilation. Once you have a compilation, you can get all the info from this compilation. Not just from the added reference ( mscorlib in your case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM