目录: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