解析C#类文件以获取属性和方法属性、文件、方法

2023-09-04 02:45:28 作者:我的好过期不候

可能重复:   解析器的C#

说,如果我有一个简单的类,如在一个WinForms应用程序中的文本框控件中:

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:

类名 属性 在任何公共方法

任何意见/建议AP preciated。

Any ideas/suggestions appreciated.

推荐答案

您可以使用的反射为:

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);

接下来,你应该确认,如果你的文本是一个有效的C#code。其实你code是无效的 - 方法DoSomething的标记为无效,但它返回一个字符串

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();    
}