抽象工厂核心反射

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

namespace TestReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            IName objChineseName = AbstractFactory.createChineseName();
            objChineseName.ShowName();

            IName objEnglishName = AbstractFactory.createChineseName();
            objEnglishName.ShowName();
        }
    }

    // 声明一个接口,它有一个显示"名字"的功能(ShowName方法)
    public interface IName
    {
        void ShowName();
    }

    // 实现接口,显示中国名字
    public class ChineseName : IName
    {
        IName 成员
    }

    // 实现接口,显示中国名字
    public class EnglishName : IName
    {
        IName 成员
    }

    // 最为重要的代码段,往下看
    // 使用抽象工厂的方法来进行动态创建对象实例应用哦
    public sealed class AbstractFactory
    {
        public static readonly string path = "TestReflection";

        public static IName createChineseName()
        {
            // s 的值以后从Web.Config动态读取,如下所示
            /*    
                   
                 
             */
            // 把className赋值为:TestReflection.ChineseName,将显示中文名
            string className = path + ".ChineseName";
            return (IName)Assembly.Load(path).CreateInstance(className);
        }

        public static IName createEnglishName()
        {
            string className = path + ".EnglishName";
            return (IName)Assembly.Load(path).CreateInstance(className);
        }
    }
}

如果你不太清楚自己的解决方案中都用到了哪些Assembly,可以使用下面的方法,如果再想得到Assembly里的信息

 

namespace TestReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            // 遍历显示每个Assembly的名字
            foreach (object var in Ax)
            {
                Console.WriteLine("Assembly的名字是:" + var.ToString());

                // 使用一个已知的Assembly的名称,来创建一个Assembly
                // 通过CodeBase属性显示最初指定的程序集的位置
                Console.WriteLine("最初指定的程序集TestReflection的位置:" + Assembly.Load("TestReflection").CodeBase);
                Console.ReadLine();
            }
        }
    }
}

 

 

 

 

posted @ 2014-02-26 14:59  思想启蒙家  阅读(171)  评论(0编辑  收藏  举报