0

Give C# code file, for example:


using System;
namespace std
{
class HelloWorld
{
static void Main(string\[\] args)
{
**Console.WriteLine("Hello World!");**
**Console.ReadKey();**
}}}

How to resovle the fully qualified name of each code elements with Roslyn? Just like:


using System;
namespace std
{
class HelloWorld
{
static void Main(string\[\] args)
{
**System.Console.WriteLine("Hello World!");**
**System.Console.ReadKey();**
}}}

The Console.ReadKey() be resolved into System.Console.ReadKey();

I have tryed with this code, but I failed. Here is my written code.


namespace SyntaxWalker
{
class Program
{
const string programText =
@"using System;
using System.Collections.Generic;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string\[\] args)
{
Console.WriteLine(""Hello, World!"");
}
}
}";
static void Main(string\[\] args)
{
SyntaxTree tree = CSharpSyntaxTree.ParseText(programText);
CompilationUnitSyntax root = tree.GetCompilationUnitRoot();

            var collector = new Collector();
            collector.Visit(root);
            foreach (var eps in collector.EPS)
            {  
               //  Here is my question
               //  Here, I want to get the fully-qualified name of **Console.WriteLine**, that is **System.Console.WriteLine**. But I don't know which APIs can obtain this fully-qualified name.
                WriteLine(eps.Expression);  //  the result is  Console.WriteLine(""Hello, World!"");

            }
        }
    }

class Collector : CSharpSyntaxWalker
{
        public ICollection<ExpressionStatementSyntax>  EPS{ get; } = new List<ExpressionStatementSyntax>();
        public override void VisitExpressionStatement (ExpressionStatementSyntax node)
        {
            EPS.Add(node);
        }
    }
}

My problem is detailed in the code's comments above, is there a better way to solve this?

  • It's not a Syntax level problem. Syntax just describes what is written in a source text. You might have to obtain a Semantic model from the syntax tree. See this article: https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/get-started/semantic-analysis – Yevhen Cherkes Nov 08 '22 at 08:27

0 Answers0