Get a method's contents from a cs file

前端 未结 6 1717
孤独总比滥情好
孤独总比滥情好 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:05

    Assuming that the file is valid (i.e. compiles), you can start by reading the whole file into a string.

    I gather from your question that you are only interested in method names, not in class names. Then you need a regex that gives you all instances of public|protected|private, optional keywords virtual/override etc, MethodName, (, optional parameters, ). It would help if there were coding conventions, so you could assume that all method definitions were always in one line, not spread over several lines.

    Once you have that, it is only a matter of counting { and } to get the function body.

    And one final advice: Beware of assumptions. They have the nasty habbit of biting you in the butt.

    EDIT: Ouch, forgot about comments! if you have brackets in comments in the method body, your counting can go wrong. So you need to strip all comments from the source as your very first step.

提交回复
热议问题