黑马程序员技术交流社区

标题: 反射 [打印本页]

作者: 杨本国    时间: 2011-11-30 18:19
标题: 反射
我看了点点反射的东西,看不懂啊、、、不知哪位大侠能给个简单的实例应用啊?
作者: 杨楠    时间: 2011-11-30 19:15
一起等简单易懂的解释
作者: 董志    时间: 2011-12-2 14:41
反射一词出现在面向对象程序设计中,主要用于获取变量或类的相关信息,比如变量的类型,类的构造方法,字段信息,成员函数信息,属性信息。
主要使用Type类中的GetType方法

下面示例演示如何列出String类的构造函数
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;

  6. namespace Reflection
  7. {
  8.     class Program
  9.     {
  10.         public static void PrintMembers(MemberInfo[] ms) {
  11.             foreach (MemberInfo m in ms) {
  12.                 Console.WriteLine("{0}{1}","    ",m);
  13.             }
  14.             Console.WriteLine();
  15.         }
  16.         static void Main(string[] args)
  17.         {
  18.             Type t = typeof(System.String);
  19.             Console.WriteLine("Listint all the public constructors of the {0} type",t);
  20.             ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
  21.             Console.WriteLine("//Constructors");
  22.             PrintMembers(ci);
  23.             Console.ReadKey();
  24.         }
  25.     }
  26. }
复制代码
使用MemberInfo、MethodInfo、FieldInfo、PropertyInfo对象可以获得有关类型的方法、属性、事件、字段的信息。
下面就MemberInfo对象做简单演示
  1. static void Main(string[] args)
  2.         {
  3.             Console.WriteLine("\nReflection.MemberInfo");
  4.             Type MyType = Type.GetType("System.IO.File");
  5.             MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
  6.             Console.WriteLine("\nThere are {0} members in {1}.",Mymemberinfoarray.Length,MyType.FullName);
  7.             Console.WriteLine("{0}.",MyType.FullName);
  8.             if (MyType.IsPublic) {
  9.                 Console.WriteLine("{0} is public.",MyType.FullName);
  10.             }
  11.             foreach (MemberInfo m in Mymemberinfoarray) {
  12.                 Console.WriteLine(m.ToString());
  13.             }
  14.             Console.ReadKey();
  15.         }
复制代码

作者: 闫炳颖    时间: 2011-12-4 19:31
反射,你需要using 一下 system.reflection 命名空间,然后使用Assembly类中的某些方法来反射程序集咯,所谓程序集可以简单理解为.exe或.dll文件,也就是你用C#做完的程序编译得到的东西。具体使用场合,比如程序自动升级中反射得到版本号,比如分层项目中如果使用抽象工厂模式等,可以在运行时反射得到某些类的实例等。
说白了就是把一个类(不管你是已知还是未知),可以反射出它的属性、方法、变量。
作者: 何旭    时间: 2011-12-12 11:47
可以参看我的博客:(反射的简单理解)http://www.cnblogs.com/cilence/archive/2011/12/12/2284623.html




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2