反射略识

2021-04-23
反射略识

using System;

using System.Collections.Generic;

using System.Linq;

using System.Reflection;

using System.Text;

using System.Threading.Tasks;



namespace 反射练习

{

    class Program

    {

        static void Main(string[] args)

        {

            NewClassw nc = new NewClassw();

            Type t = nc.GetType();



            object obj = Activator.CreateInstance(t);//反射生成对象

            //取得ID字段 

            FieldInfo fi = t.GetField("ID");

            //给ID字段赋值 

            fi.SetValue(obj, "k001");

            //取得MyName属性 

            PropertyInfo pi1 = t.GetProperty("MyName");

            //给MyName属性赋值 

            pi1.SetValue(obj, "grayworm", null);

            PropertyInfo pi2 = t.GetProperty("MyInfo");

            pi2.SetValue(obj, "hi.baidu.com/grayworm", null);

            //取得show方法 

            MethodInfo mi = t.GetMethod("show");

            //调用show方法 

            mi.Invoke(obj, null);

            ConstructorInfo[] ci = t.GetConstructors();    //获取类的所有构造函数

            foreach (ConstructorInfo c in ci) //遍历每一个构造函数

            {

                ParameterInfo[] ps = c.GetParameters();    //取出每个构造函数的所有参数

                foreach (ParameterInfo pi in ps)   //遍历并打印所该构造函数的所有参数

                {

                    Console.Write(pi.ParameterType.ToString() + " " + pi.Name + ",");

                }

                Console.WriteLine();

            }



           

            //MethodInfo[] mis = t.GetMethods();

            //foreach (MethodInfo mi in mis)//获取public方法

            //{

            //    Console.WriteLine(mi.ReturnType + " " + mi.Name);

            //}

            //FieldInfo[] fis = t.GetFields();

            //foreach (FieldInfo fi in fis)//获取属性列表

            //{

            //    Console.WriteLine(fi.Name);

            //} 

            Console.ReadLine();

        }

    }



     public class NewClassw

     {

         public NewClassw()

         {

         }



         public NewClassw(int a)

         {

         }

         public NewClassw(int a, int b)

          {

          }

         public NewClassw(string a, int b)

          {

          }



         public int Fun1(string wc)

         {

             return 0;

         }



         public void Fun2(int wc)

         {

         }

     }



}