c#反射

目录:c#高级编程学习笔记

using System;
using System.Reflection;
class A{
	public void fun(){
		Console.WriteLine("A fun");
	}
	public void fun2(int a){
		Console.WriteLine("A fun2"+ a);
	}
	public int fun3(int a){
		return a;
	}
}
class B{
	public int ma;
	public B(int a){
		ma = a;
	}
}
class HelloWorld
{
    	static void Main(string[] args)
      	{
         	Console.WriteLine("反射实验");
		Type  t  =  Type.GetType("A");
		// 无参构造
		A a = (A)Activator.CreateInstance(t);
		a.fun();
		
		// 无参函数
		MethodInfo  method  =  t.GetMethod("fun");
		Object[] chanshu0 = new Object[]{};
		method.Invoke(a,chanshu0);
		// 有参函数
		MethodInfo  method2  =  t.GetMethod("fun2");
		Object[] chanshu1 = new Object[]{5};
		method2.Invoke(a,chanshu1);
		// 返回值函数
		MethodInfo  method3  =  t.GetMethod("fun3");
		Object[] chanshu3 = new Object[]{6};
		Object re3 = method3.Invoke(a,chanshu3);
		Console.WriteLine(re3);

		// 有参构造
		Type  tb  =  Type.GetType("B");
		Object[] chanshu = new Object[]{5};
		B ob = (B)Activator.CreateInstance(tb ,chanshu);
		Console.WriteLine(ob.ma);
		// 成员访问
		FieldInfo myfield = tb.GetField("ma");
		int ma = (int)myfield.GetValue(ob);
		Console.WriteLine("ma:"+ma);

         	Console.ReadKey();
      	}
}

引用
https://www.cnblogs.com/wangshenhe/p/3256657.html
https://www.cnblogs.com/Stephenchao/p/4481995.html
https://www.runoob.com/csharp/csharp-reflection.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值