数字化世界

关于反射的学习

前边看抽象工厂模式时,对反射有些不熟悉,这两天学习了一下,把成果记下来。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReflectTest
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(@"D:\\liujisong\\Documents\\Visual Studio 2012\\Projects\\TestDesignPattern\\TransportStyle\\bin\\Debug\\TransportStyle.dll");
            //Type[] t = a.GetTypes();

            //foreach (Type objType in t)
            //{
            //    string s = objType.ToString();
            //    object objClass = a.CreateInstance(s);
            //    System.Reflection.MethodInfo method = objType.GetMethod("reuturn");
            //    Console.WriteLine(method.Invoke(objClass, null));
            //}

            object obj;

            //想要调用的程序集中的类中的方法
            System.Reflection.MethodInfo method = assembly.GetType("TransportStyle.Car").GetMethod("reuturn");

            //类的实例
            obj = assembly.CreateInstance("TransportStyle.Car");

            //取得方法返回值
            string s = (string)method.Invoke(obj, null);

            Console.WriteLine(s);
            Console.ReadKey();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TransportStyle
{
    public class Translation
    {
        public Translation()
        {
 
        }

        public virtual string reuturn()
        {
            return "this is 交通工具";
        }
    }

    public class Car : Translation
    {
        public override string reuturn()
        {
            return "this is 汽车";
        }
    }

    public class Ship : Translation
    {
        public override string reuturn()
        {
            return "this is 轮船";
        }
    }

    public class Plan : Translation
    {
        public override string reuturn()
        {
            return "this is 飞机";
        }
    }
}

这只是基础的,有时间再继续往深处钻钻!

posted on 2014-07-10 17:13  数字化世界  阅读(126)  评论(0)    收藏  举报

导航