C#__Basic usage of using Type class to reflect data

 // a brief introdction

// Metadata: Data related to the program and its type.
// Reflection: The behavior of a running program to view its own metadata or metadata in other assemblies
// Assembly class: allows access to the metadata of a given assembly, including the assembly that can be loaded and executed

//Define a class MyClass for access

    class MyClass
    {
        private int a, b;
        public int c;
        public string d;

        public string Name1 { get; set; }
        public string Name2 { get; set; }
        public void Test1() { }
        public void Test2() { }
    }

//Main function call

    class Program
    {
        static void Main(string[] args)
        {
            // 使用Type类可以反射数据
            // 定义

            // 方案一
            Type t1 = typeof(MyClass);
            // 方案二
            MyClass myclass = new MyClass();
            Type t2 = myclass.GetType();
            
            // 获取类名
            Console.WriteLine(t1.Name); // MyClass
            Console.WriteLine(t2.Name); // MyClass
            // 获取空间名
            Console.WriteLine(t1.Namespace); // TypeAndAssembly
            Console.WriteLine(t2.Namespace); // TypeAndAssembly
            // 获取程序集的基本信息 (空间名,版本,文化,公共钥匙符号)
            Console.WriteLine(t1.Assembly); // TypeAndAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
            Console.WriteLine(t2.Assembly); // TypeAndAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

            // 提取MyClass的字段的属性
            FieldInfo[] fis = t1.GetFields();
            foreach (FieldInfo fi in fis)
            {
                Console.WriteLine(fi.Name); 
                //c
                //d
            }

            // 提取MyClass的属性的 get 访问器。
            PropertyInfo[] pis = t2.GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                Console.WriteLine(pi); 
                // System.String Name1
                // System.String Name2
            }

            // 提取Myclass的类函数(包含继承自父类的)
            MethodInfo[] mis = t2.GetMethods();
            foreach (MethodInfo mi in mis)
            {
                Console.WriteLine(mi);
                /*
                System.String get_Name1()
                Void set_Name1(System.String)
                System.String get_Name2()
                Void set_Name2(System.String)
                Void Test1()
                Void Test2()
                Boolean Equals(System.Object)
                Int32 GetHashCode()
                System.Type GetType()
                System.String ToString()
                 */
            }
        }
    }

Guess you like

Origin blog.csdn.net/qq_57233919/article/details/132338296