c#反射机制
例子:
using System;
using System.Collections.Generic; using System.Linq; using System.Text; namespace ITOO.Reflection.Student { public class Student { public string Name { get; set; } public int Age { get; set; } // 默认构造函数 public Student() { this.Age = 24; this.Name = "连江伟"; } //带参数的构造函数 public Student(string name,int age) { this.Name = name; this.Age = age; } public void Hello() { Console.WriteLine("我是"+Name +",我今年"+Age +"岁了!"); } } }
利用反射操纵这个类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ITOO.Reflection.Client
{
class Program
{
static void Main(string[] args)
{
//动态加载DLL,这个LoadFile最方便,参数就是dll的路径。
var asm = Assembly.LoadFile(@"C:\Users\ljw\Desktop\学习例子\ITOO.Reflection.Test\ITOO.Reflection.Student\bin\Debug\ITOO.Reflection.Student.dll");
//获取Student类的类型
var type = asm.GetType("ITOO.Reflection.Student.Student");
//创建该类的实例
var instance = asm.CreateInstance("ITOO.Reflection.Student.Student");
//为学生类的属性赋值
type.GetProperty("Name").SetValue(instance, "段天涯", null);
type.GetProperty("Age").SetValue(instance, 18, null);
//获取Student类的方法
var method = type.GetMethod("Hello");
//调用Student类的成员方法Hello
method.Invoke(instance, null);
Console.Read();
}
}
}

浙公网安备 33010602011771号