using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
namespace SampleCode
{
class Program
{
static void Main(string[] args)
{
}
}
public class Student
{
Teacher _teacher;
public Student()
{
}
public string Name { get; set; }
public string Age { get; set; }
public Teacher Teacher { get => _teacher; set => _teacher = value; }
}
public class Teacher
{
public Teacher()
{
}
public string Name { get; set; }
public string Degree {
get; set; }
}
}
using
Microsoft.CodeAnalysis;
using
Microsoft.CodeAnalysis.CSharp;
using
Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace AST4CSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void
Form1_Load(object sender, EventArgs e)
{
string sourceCode =
@"using
System;
using
System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleCode
{
class Program
{
static void
Main(string[] args)
{
}
}
public class Student
{
Teacher _teacher;
public Student()
{
}
public string Name {
get; set; }
public string Age {
get; set; }
public Teacher Teacher
{ get => _teacher; set => _teacher = value; }
}
public class Teacher
{
public Teacher()
{
}
public string Name {
get; set; }
public string Degree {
get; set; }
}
}";
SyntaxTree tree =
CSharpSyntaxTree.ParseText(sourceCode);
CompilationUnitSyntax root =
tree.GetCompilationUnitRoot();
var finder = new
ClassFinder();
finder.Visit(root);
foreach (var c in
finder.classes)
{
Console.WriteLine(c.Identifier.Text);
}
}
public class ClassFinder : CSharpSyntaxWalker
{
public ICollection<ClassDeclarationSyntax> classes { get; } = new List<ClassDeclarationSyntax>();
public override void
VisitClassDeclaration(ClassDeclarationSyntax node)
{
classes.Add(node);
base.VisitClassDeclaration(node);
}
}
}
}
Program
Student
Teacher