简体   繁体   中英

How to generate Semantic Model from code file without project file using Roslyn

I have two file as below:

namespace a
{
    Class Audi
    {
            public string Model(string a)
            {           
               Benz obj= new Benz();
               var str=obj.BenzDetails();
               return str;

            }
    }
}
namespace a
{
    Class Benz 
    {
            public string BenzDetails()
            {           
              return "some details";
            }
    }
}

I need to get all objects created in Audi Class (Global or local). Also i need to get details of methods invoked using these declared object.

For example in these 2 classes, for Audi class need:

  • Object created :- obj
  • Method invoked using this object :- BenzDetails
  • name of class whose object is created: Benz
  • namespace of that class: a

I am able to get list of declared objects in a class with this code:

 var lstLocalObjects = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>()
                                                .Where(x => x.Declaration.Variables.Any(p => p.Initializer.Value.Kind().ToString().Equals("ObjectCreationExpression", StringComparison.OrdinalIgnoreCase)));

I have syntax tree, I don't know how to generate Semantic Model. Is it possible to get above details using syntax tree only. Please help. Thank you

You need to create a Compilation by calling CSharpCompilation.Create() , passing your SyntaxTree and the necessary references (at least mscorlib ).

You can then call GetSemanticModel(SyntaxTree) .

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