C#获取某个class类的字段、属性、方法 详解(亲测有用)

  1. 先放一个测试的类 TestA
    class TestA
    {
    private int a { set; get; }
    private string b { set; get; }
    private bool c { set; get; }

        /// 
        /// 测试方法1
        /// 
        public void csMesthod1() {
            MessageBox.Show("我是方法1");
        }
    }
    

2.然后直接在调用的方法中写正经代码

TestA ta = new TestA();
object obj = ta;
Type t = obj.GetType();//获取对象类型
//保存属性的字符串
string strS = “”;
strS += “字段:\n”;
foreach (FieldInfo fi in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
strS+=(“名称:” + fi.Name + “,类型:” + fi.FieldType.Name+“\n”);

        strS += "属性:\n";
        foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
           strS+=("名称:" + pi.Name + ",类型:" + pi.PropertyType.Name+"\n");
           
        strS += "方法:\n";
        foreach (MethodInfo mi in t.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
           strS+=("名称:" + mi.Name + ",返回类型:" + mi.ReturnType.Name+"\n");

      此时的strS字符串得到的就是我们将字段属性方法集于一体的字符串内

你可能感兴趣的:(c#,开发语言)