解析C#类文件以获取属性和方法 [英] Parse c# class file to get properties and methods

查看:165
本文介绍了解析C#类文件以获取属性和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  解析器的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();    
}

这篇关于解析C#类文件以获取属性和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆