Regex to parse C# source code [duplicate]

2019-07-24 15:11发布

This question already has an answer here:

i am in the process of creation of simple Document Map for the following C# source.

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public string DoSomething(string x)
    {
        return "Hello " + x;
    }
}

The results should be presented in treeview or listview, in following manner:

Person
-- Name
-- Age
-- DoSomething()

So, question is, is there a regex or library which handles C# source code?

标签: c# regex parsing
2条回答
别忘想泡老子
2楼-- · 2019-07-24 15:45

Visual Studio already has something of the sort. you can use the arrow next to a CS file to click through and get a list of all methods and variables in that file. it even shows a padlock if they're private.

查看更多
神经病院院长
3楼-- · 2019-07-24 15:52

You absolutely cannot use a regex to parse C# source as C# does not have a regular grammar.

You could use Roslyn though: http://blogs.msdn.com/b/csharpfaq/archive/2011/10/19/introducing-the-microsoft-roslyn-ctp.aspx

Alternatively, use the current C# compiler (or the System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource() method) to compile the code to a new assembly, load that assembly and use reflection to analyse it.

查看更多
登录 后发表回答