Get types used inside a C# method body

后端 未结 7 871
鱼传尺愫
鱼传尺愫 2020-12-01 16:12

Is there a way to get all types used inside C# method?

For example,

public int foo(string str)
{
    Bar bar = new Bar();
    string x = \"test\";
           


        
7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 17:09

    As others have mentioned, if you had the DLL you could use something similar to what ILSpy does in its Analyze feature (iterating over all the IL instructions in the assembly to find references to a specific type).

    Otherwise, there is no way to do it without parsing the text into a C# Abstract Syntax Tree, AND employing a Resolver - something that can understand the semantics of the code well enough to know if "Bar" in your example is indeed a name of a type that is accessible from that method (in its "using" scope), or perhaps the name of a method, member field, etc... SharpDevelop contains a C# parser (called "NRefactory") and also contains such a Resolver, you can look into pursuing that option by looking at this thread, but beware that it is a fair amount of work to set it up to work right.

提交回复
热议问题