反射学习

反射学习
反射是.NET中的重要机制,通过反射,可以在运行时获得.NET中的每一个类型(包括类、结构、委托、接口和枚举)的成员,包括方法、属性、事件,以及构造函数。还可以获得每个成员的名称,限定符和参数等,有了反射,即可对每一个类型了如指掌。
建立ClassLib类库
ClassPerson.cs类
using System; 
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLib
{
    class ClassPerson
    {
        public ClassPerson() :this(null){ 

        }
        public ClassPerson(string strname) {
            name = strname;
        }
        private string name = null;

        public string Name
        {
          get { return name; }
          set { name = value; }
        }
        private string sex=null;
        public string Sex {
            get { return sex; }
            set { name = value; }
        }
        private int age;
        public int Age {
            get { return age; }
            set { age = value; }
        }
        public void SayHello() {
            if (name == null)
            {
                System.Console.WriteLine("Hello World!");
            }
            else {
                Console.WriteLine("Hello {0}", Name);
            }
        }

    }
}
 
 
 

MethodInfo 类

发现方法的特性并提供对方法元数据的访问。

 
using System; 
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("列出程序集中所有类型");
            Assembly ass = Assembly.LoadFrom("ClassLib.dll");
            Type classPerson = null;
            Type[] myTypes=ass.GetTypes();
            foreach (Type t in myTypes) {
                Console.WriteLine(t.Name);
                if (t.Name == "ClassPerson") {
                    classPerson = t;
                }
            }
            Console.WriteLine("列出ClassPerson类中的所有方法");
            MethodInfo[] mif = classPerson.GetMethods();
            foreach (MethodInfo mf in mif) {
                Console.WriteLine(mf.Name);
            }
            Console.WriteLine("实例化ClassPerson,并调用SayHello方法");
            Object obj = Activator.CreateInstance(classPerson);
            Object objName = Activator.CreateInstance(classPerson, "litianping");
            MethodInfo msayhello = classPerson.GetMethod("SayHello");
            msayhello.Invoke(obj, null);
            msayhello.Invoke(objName, null);
            System.Console.ReadLine();
        }
    }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 




附件列表

     

    posted @ 2011-10-22 22:40  .windy  阅读(153)  评论(0编辑  收藏  举报