码迷,mamicode.com
首页 > Web开发 > 详细

.NET反射应用

时间:2015-03-18 13:42:34      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

     .Net中,在编写框架时,反射是最长用的一个知识点,在这举个小例子,旨在说明反射如何应用;本文只程序中只涉及到System.Type的应用,通过这个类可以访问关于任何数据类型的信息,注释部分涉及到System.Reflection.Assembly类,该类用于访问给定程序集的相关信息,或者把这个程序集加载到程序中。
示例代码:

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

namespace ConsoleReflect
{
    class Program
    {
        static void Main(string[] args)
        {
            ///对类库的调用,不详解
            //Assembly assmbly = Assembly.LoadFile("类库目录");
            //Type[] lstType = assmbly.GetExportedTypes();
            List<Type> lstType = new List<Type>();
            string a = new Program().GetType().Namespace;
            Type typeA = Type.GetType(new Program().GetType().Namespace + "." + "PrinterA", true, true);
            Type typeB = Type.GetType(new Program().GetType().Namespace + "." + "PrinterB", true, true);
            lstType.Add(typeA);
            lstType.Add(typeB);
            foreach (Type type in lstType)
            {
                var temp = Activator.CreateInstance(type);
                MethodInfo method = type.GetMethod("Print");
                object[] obj = new object[1];
                obj[0] = type.Name;
                method.Invoke(temp, obj);
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleReflect
{
    class PrinterA
    {
        public void Print(object obj)
        {
            if (obj != null)
            {
                Console.WriteLine(obj.ToString());
            }
            else
            {
                Console.WriteLine("PrinterA参数为空!");
                Console.Read();
            }
        }
    }
}

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

namespace ConsoleReflect
{
    class PrinterB
    {
        public void Print(object obj)
        {
            if (obj != null)
            {
                Console.WriteLine(obj.ToString());
                Console.Read();
            }
            else
            {
                Console.WriteLine("PrinterB参数为空!");
                Console.Read();
            }
        }
    }
}

 

.NET反射应用

标签:

原文地址:http://www.cnblogs.com/sumuncle/p/4346873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!