szujason
在程序的世界里,我们都是王!

  反射的作用有很多,但这里只介绍最基本也是最常用的反射运用。

  利用反射可以使我们在程序运行时才定义一些变量的类型,增强了程序的变化性,又不用修改源代码。

  方法:使用Assembly定义和加载程序集,加载在程序清单中列出的模块,以及从此程序集中查找类型并创建该类型的实力。


  定义了IPrint输出东西的接口类,只有Output方法,就是输出方法

  定义了PrintB类,继承IPrint接口类,实现了Output方法。

  定义了FactoryPrint类,定义了一个static类型的InstancePrint方法, 通过传进类名返回该类的一个实例

  定义了Program主类,通过在控制台动态的输入一个类名,从而实例化该类的一个实例,然后调用该实例的Output方法。

 

  下面是我写得简单的代码样例。

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace MyReflectionDemo
{
    interface IPrint
    {
        void Output();
    }

    class PrintA : IPrint
    {
        public void Output()
        {
            Console.WriteLine("这是PrintA");
        }
    }

    class PrintB : IPrint
    {
        public void Output()
        {
            Console.WriteLine("这是PrintB");
        }
    }

    class FactoryPrint
    {
        private static readonly string AssemblyName = "MyReflectionDemo";
        public static IPrint InstancePrint(string className)
        {
            string ClassName = AssemblyName + "." + className;//类名
            return (IPrint)Assembly.Load(AssemblyName).CreateInstance(ClassName);//返回ClassName类型的一个实例
        }

    }

 

    class Program
    {
        static void Main(string[] args)
        {
            string className = Console.ReadLine();
            IPrint print = FactoryPrint.InstancePrint(className);
            print.Output();
            Console.Read();
        }
    }

}

 

 

输入:PrintA时

输出:这是PrintA

输入:PrintB时

输出:这是PrintB

 


posted on 2009-05-20 15:27  szuJason  阅读(137)  评论(0)    收藏  举报