首页 > 技术文章 > C# 反射

2zhyi 2014-02-11 14:31 原文

反射 提供了对程序集,模块和类型的对象,可以使用反射动态创建类型的实例,或从现有的对象提供获取类型并调用其方法或访问其字段和属性。如果代码中使用了属性,可以利用反射对他们进行访问。

反射的性能损失主要来源于比较类型,遍历成员,调用成员三种情形,其中比较类型耗时最小,调用成员耗时最多,所以尽量减少采用成员动态调用等反射方式可以提高应用程序性能。除此之外,采取后期绑定,避免将反射方法放到循环内产生放大效应等办法均可以提升反射性能

 

using Loger;
using System;
using System.Data;
using System.Reflection;



namespace Module1
{

    public class Person
    {
        private int id = 0;

        public string Name
        {
            get;
            set;
        }

        public Person()
        {

        }

        public Person(string name)
        {
            this.Name = name;
        }

        public string GetName()
        {
            return this.Name;
        }

        public string GetValue(string prefix)
        {
            return prefix;
        }

        public bool MySex()
        {
            return true;
        }

    }

}



namespace ConsoleApplication1
{
    class Program
    {

        private static string instanceSpec = "System.EventArgs;System.Random;" + "System.Exception;System.Object;System.Version";

        static void Main(string[] args)
        {

            //Type t = Type.GetType("Module1.Person");
            //object[] para = new object[] { "Joey" };
            //Module1.Person p = (Module1.Person)Activator.CreateInstance(t, para);
            //Console.WriteLine(p.Name);

            Type t = Type.GetType("Module1.Person");
            object[] para = new object[] { "Joey" };
            object obj = Activator.CreateInstance(t, para);
            MethodInfo method = t.GetMethod("MySex");
            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance;
            //object[] paraValue = new object[] { "Test" };
            object getValue = method.Invoke(obj, flag, Type.DefaultBinder, null, null);



            //Assembly asm = Assembly.LoadFrom(@"D:\VSProjectsSource\VAU\Loger\bin\Debug\Loger.dll");
            //ILogInterface logger = null;
            //foreach (Type t in asm.GetTypes())
            //{
            //    //if (t.GetInterface("ILogInterface") != null)
            //    if (t.Name.Equals("JoelsLogger"))
            //    {
            //        logger = (ILogInterface)Activator.CreateInstance(t);
            //        break;
            //    }
            //}
            //if (logger != null)
            //    logger.WriteApplicationEvent("Initialized...");

            //Type t = Type.GetType("System.Data.DataTable,System.Data,Version=1.0.3300.0,  Culture=neutral,  PublicKeyToken=b77a5c561934e089");
            //DataTable table = (DataTable)Activator.CreateInstance(t);


            //string[] instances = instanceSpec.Split(';');
            //Array instlist = Array.CreateInstance(typeof(object), instances.Length);
            //object item;
            //for (int i = 0; i < instances.Length; i++)
            //{
            //    // create the object from the specification string
            //    Console.WriteLine("Creating instance of: {0}", instances[i]);
            //    item = Activator.CreateInstance(Type.GetType(instances[i]));
            //    instlist.SetValue(item, i);
            //}
            //Console.WriteLine("\nObjects and their default values:\n");
            //foreach (object o in instlist)
            //{
            //    Console.WriteLine("Type:     {0}\nValue:    {1}\nHashCode: {2}\n",
            //        o.GetType().FullName, o.ToString(), o.GetHashCode());
            //}

            Console.Read();

        }
    }
}

 

例子: 

 

http://msdn.microsoft.com/zh-cn/magazine/cc163759(en-us).aspx

 

http://www.cnblogs.com/wangshenhe/p/3256657.html

推荐阅读