(转)反射技术示例

using System;
using System.Collections.Generic;
using System.Text;
 
namespace ReflectionDemo
{
    public class HelloWorld
    {
        private string strName = null;
        public HelloWorld(string name)
        {
            strName = name;
        }
        public HelloWorld()
        {
        }
        public string Name
        {
            get
            {
                return strName;
            }
        }
        public void SayHello()
        {
            if (strName == null)
            {
                System.Console.WriteLine("Hello World");
            }
            else
            {
                System.Console.WriteLine("Hello World,"+strName);
            }
        }
 
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
 
namespace ReflectionDemo
{
        class Program
        {
            static void Main(string[] args)
            {
                System.Console.WriteLine("列出程序集中的所有类型");
                Assembly a = Assembly.LoadFrom ("ReflectionDemo.exe");
                Type[] mytypes = a.GetTypes( );
 
                foreach (Type t in mytypes)
                {
                  System.Console.WriteLine ( t.Name );
                }
                System.Console.ReadLine ( );
 
                System.Console.WriteLine ("列出HellWord中的所有方法" );
                Type ht = typeof(HelloWorld);
                MethodInfo[] mif = ht.GetMethods();
                foreach(MethodInfo mf in mif)
                {
                  System.Console.WriteLine(mf.Name);
                }
                System.Console.ReadLine();
 
                System.Console.WriteLine("实例化HelloWorld,并调用SayHello方法");
                Object obj = Activator.CreateInstance(ht); //调用无参数构造函数
 
                string[] s = {"wangjing"};
                Object objName = Activator.CreateInstance(ht, s); //调用参数构造函数
                 MethodInfo msayhello = ht.GetMethod("SayHello");
                msayhello.Invoke(obj,null);
                msayhello.Invoke(objName,null);
                System.Console.ReadLine();
 
                }
            }
    }
 

posted on 2008-01-13 23:58  IT@民工  阅读(126)  评论(0编辑  收藏  举报

导航