使用反射实现延迟绑定

王朝学院·作者佚名  2016-05-17
窄屏简体版  字體: 小  |  中  |  大  |  超大  

使用反射实现延迟绑定反射允许我们在编译期或运行时获取程序集的元数据,通过反射可以做到:● 创建类型的实例● 触发方法● 获取属性、字段信息● 延迟绑定......

如果在编译期使用反射,可通过如下2种方式获取程序集Type类型:1、Type类的静态方法Type type = Type.GetType("somenamespace.someclass");

2、通过typeofType type = typeof(someclass);

如果在运行时使用反射,通过运行时的Assembly实例方法获取Type类型:

Type type = asm.GetType("somenamespace.someclass");

获取反射信息

有这样的一个类:

public class Student { public int Id { get; set; } public string Name { get; set; } public float Score { get; set; } public Student() { this.Id = -1; this.Name = string.Empty; this.Score = 0; } public Student(int id, string name, float score) { this.Id = id; this.Name = name; this.Score = score; } public string DisplayName(string name) { return string.Format("学生姓名:{0}", name); } public void ShowScore() { Console.WriteLine("学生分数是:" + this.Score); } }

通过如下获取反射信息:

static void Main(string[] args) { Type type = Type.GetType("Consoleapplication1.Student"); //Type type = typeof (Student); Console.WriteLine(type.FullName); Console.WriteLine(type.Namespace); Console.WriteLine(type.Name); //获取属性 PRopertyInfo[] props = type.GetProperties(); foreach (PropertyInfo prop in props) { Console.WriteLine(prop.Name); } //获取方法 MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo method in methods) { Console.WriteLine(method.ReturnType.Name); Console.WriteLine(method.Name); } Console.ReadKey(); }

延迟绑定

在通常情况下,为对象实例赋值是发生在编译期,如下:Student stu = new Student();stu.Name = "somename";

而"延迟绑定",为对象实例赋值或调用其方法是发生在运行时,需要获取在运行时的程序集、Type类型、方法、属性等。

//获取运行时的程序集 Assembly asm = Assembly.GetExecutingAssembly(); //获取运行时的Type类型 Type type = asm.GetType("ConsoleApplication1.Student"); //获取运行时的对象实例 object stu = Activator.CreateInstance(type); //获取运行时指定方法 MethodInfo method = type.GetMethod("DisplayName"); object[] parameters = new object[1]; parameters[0] = "Darren"; //触发运行时的方法 string result = (string)method.Invoke(stu, parameters); Console.WriteLine(result); Console.ReadKey();

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航