Parse c# class file to get properties and methods
10,746
Solution 1
You can use Reflection for that:
Type type = typeof(Person);
var properties = type.GetProperties(); // public properties
var methods = type.GetMethods(); // public methods
var name = type.Name;
UPDATE First step for you is compiling your class
sring source = textbox.Text;
CompilerParameters parameters = new CompilerParameters() {
GenerateExecutable = false,
GenerateInMemory = true
};
var provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromSource(parameters, source);
Next you should verify if your text is a valid c# code. Actually your code is not valid - method DoSomething marked as void, but it returns a string.
if (results.Errors.HasErrors)
{
foreach(var error in results.Errors)
MessageBox.Show(error.ToString());
return;
}
So far so good. Now get types from your compiled in-memory assembly:
var assembly = results.CompiledAssembly;
var types = assembly.GetTypes();
In your case there will be only Person
type. But anyway - now you can use Reflection to get properties, methods, etc from these types:
foreach(Type type in types)
{
var name = type.Name;
var properties = type.GetProperties();
}
Solution 2
If you need to analyse C# code at runtime, take a look at Roslyn.
Author by
mjbates7
Updated on June 14, 2022Comments
-
mjbates7 almost 2 years
Possible Duplicate:
Parser for C#Say if I had a simple class such as inside a textbox control in a winforms application:
public class Person { public string Name { get; set; } public int Age { get; set; } public void DoSomething(string x) { return "Hello " + x; } }
Is there an easy way I can parse the following items from it:
- Class Name
- Properties
- Any public methods
Any ideas/suggestions appreciated.