C# 反射

来源:互联网 发布:android知乎日报源码 编辑:程序博客网 时间:2024/06/15 05:21
反射:
assembly: 程序集
Module 模块
class 类型

提供一种编程方式 让程序在运行期间获得这几个组成部分的相关信息

好处:
反射可以让你的程序在更新的时候无需重新编译,只需替换新的dll;
可以开发出来随意增删该功能的软件 提高系统的灵活性和扩展性
可以用来修改封装好的类中的东西

缺点:
反射是一种解释操作,性能慢
发射使程序内部逻辑模糊

例子:
namespace com.bblong.lp
{
public class Student
{
public string Name{set;get;}
pulbic int Age{set;get;}

public Student()
{
this.Age=24;
this.Name="zhangsan";
}


public void Hello()
{
Console.WriteLine("我是"+Name+",年龄:"+Age);


}
}

}


namespace com.bblong.lp
{
public Demo1
{
// 动态加载dll 
var asm = Assembly.LoadFile(@"C:\User\......\Com.bblong.lp.Student.dll");
// 获取Student 类型
var type = asm.GetType("Com.bblong.lp.Student");


// 创建类型的实例
var instance = asm.CreateInstance("Com.bblong.lp.Student");


// 为实例的属性赋值
type.GetProperty("Name").SetValue(instance,"bblonglp",null);
type.GetProperty("Age").SetValue(instance,26,null);


// 获取实例的方法
var method = type.GetMethod("Hello");
// 调用实例的方法
method.Invoke(instance,null);  
Console.Read();
}

}



0 0