How to get classes and methods from a .cs file using Reflections in C #.?

How to get the classes available in the .cs file. How can we get classes and methods in an assembly using

Assembly.GetTypes() and Type.GetMethods()

      

to get the class and methods in the assembly.

Likewise, how do I get all the classes present in the C # file (.cs file).? I need to get the classes in a .cs file from which I can easily get the methods inside them and other details like method parameters etc.

+1


a source to share


6 answers


Other than using the C # parser , there is no direct way to do this. You can compile the file .cs

using CSharpCodeProvider

(which only works if the file compiles on its own and you can pass all referenced assemblies to the compiler) and use reflection in the resulting assembly.



+3


a source


I recommend using the parser generator tool to generate a fast C # parser, you can use Antlr .



Also you can check this and this

+1


a source


The compiler strips all the concepts of a code file from your code as it compiles. That being said, you can probably get the information you want from debugging symbols, if available in your assembly.

0


a source


From with help in class you can always call

this.GetType()

      

or outside of the class you can always call

obj.GetType()

      

however, when you compile an application that needs reflection to work, you can no longer get your definitions from the file.

0


a source


I've done this earlier by calling the C # compiler, compiling the C # file, and then using reflection on the inferred type. This is possible if the C # file is a standalone file and does not have any dependencies.

However, the correct way would be to use a parser - something that is not easy to do. There are several options, one of which is MinosseCC.

By the way, C # 5.0 will be much easier to compile code on the fly, having the ability to compile a String and return executable code. Can't wait for it - it will definitely confuse everyone reading my code.

0


a source


First of all, there is no such thing as a .cs file in which a class is defined. A class can be marked as partial, and parts can be defined in multiple .cs files.

When compiled with debug information, the filenames for each method remain in the assembly (corresponding IL commands are marked for each line in the source file).

Unfortunately, I don't know of an easy way to get this information from a running application (without manually parsing the assembly file).

If you call the method safely, you can call it and build the stack trace in parallel (from another thread) - in the StackFrame object, you will find the original filename. But this is slow (how should you call each method to find that the filename is different) and risky (what if the method formats your hard drive?).

So, the only way you could go is to try to parse the .cs file with a parser like AntLR.

0


a source







All Articles