Get a method's contents from a cs file

前端 未结 6 1773
孤独总比滥情好
孤独总比滥情好 2021-01-19 10:40

I have a requirement to get the contents of every method in a cs file into a string. What I am looking for is when you have an input of a cs file, a dictionary is returned w

6条回答
  •  灰色年华
    2021-01-19 11:06

    In general the problem you are trying to solve is to parse the C# code in the same manner that the compiler would, and then save the contents of the functions rather than generate code. So as background for your solution you should look at c# grammars and how to parse them.

    As per StingyJack, a simple method for doing this would be to create a regex that only identifies function definitions. Then you can assume that everything in between is a function body. However that assumption will not handle things like multiple classes in the one file or even the trailing }'s at the end of a class. To handle things like that you will have to engineer a c# compiler, as processing the complete c# grammar is the only thing that will correctly identify what c# thinks is a function.

提交回复
热议问题