反射略识

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)
         {
         }
     }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值