反射,反射优化

前两天在别人的Blogs里面看到了一个反射运用的例子,对这个概念我理解的也不透彻,所以把代码放到自己的Blogs里面,供自己学习使用
用编译器执行:
   private string test1()
        
{
            
int now = System.Environment.TickCount;

            
for (int i = 0; i < 1000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    CTester aTest 
= new CTester();
                    aTest.test1();

                }

            }


            
string time = (System.Environment.TickCount - now).ToString();
            
return time;
        }

用反射(没有优化)执行
     private string test2()
        
{
            
int now = System.Environment.TickCount;
            
for (int i = 0; i < 1000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    
//Type theTest = theTest = Type.GetType("ConsoleApplication2.CTester"); ;//

                    Type theTest 
= Type.GetType("ConsoleApplication2.CTester"); ;//


                    ConsoleApplication2.CTester theobj 
= theTest.InvokeMember(null, BindingFlags.CreateInstance
                        , 
nullnullnullas ConsoleApplication2.CTester;
                    theobj.test1();
                }

            }


            
string time = (System.Environment.TickCount - now).ToString();
            
return time;
        }

优化之后的反射
  static Hashtable table = new Hashtable();
        
private string test3()
        
{
            
int now = System.Environment.TickCount;

            
for (int i = 0; i < 1000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    Type theTest 
= null;
                    
//ContainsKey 确定 System.Collections.Hashtable 是否包含特定键
                    if (table.ContainsKey("ConsoleApplication2.CTester"))
                    
{
                        theTest 
= table["ConsoleApplication2.CTester"as Type;
                    }

                    
else
                    
{
                        
//Type theTest
                        theTest = Type.GetType("ConsoleApplication2.CTester");
                        
//Hashtable table
                        table.Add("ConsoleApplication2.CTester", theTest);
                    }

                    ConsoleApplication2.CTester theobj 
= theTest.InvokeMember(null, BindingFlags.CreateInstance
                        , 
nullnullnullas ConsoleApplication2.CTester;
                    theobj.test1();
                }

            }


            
string time = (System.Environment.TickCount - now).ToString();
            
return time;
        }
加载程序集并反射
        static object InvokeMehod(string FileName,
            
string MethodName,
            
object[] Args)
        
{
            Assembly a 
= Assembly.LoadFrom(FileName);


            MethodInfo method 
= null;
            Type HereType 
= null;


            
//在模块上进行反射
            foreach (Module m in a.GetModules())
            
{
                
//表示类型声明:类类型、接口类型、数组类型、值类型、枚举类型、类型参数、泛型类型定义,以及开放或封闭构造的泛型类型。
                foreach (Type t in m.GetTypes())
                
{
                    
//发现方法的属性 (Attribute) 并提供对方法元数据的访问。
                    foreach (MethodInfo mInfo in t.GetMethods())
                    
{
                        
if (mInfo.Name == MethodName)
                        
{
                            ParameterInfo[] pInfo 
= mInfo.GetParameters();
                            
if (pInfo.Length == Args.Length)
                            
{
                                
bool same = true;
                                
for (int i = 0; i < pInfo.Length; i++)
                                
{
                                    
if (Args[i] != null && pInfo[i].ParameterType != typeof(object)
                                        
&& pInfo[i].ParameterType != typeof(object[]))
                                    
{
                                        
if (pInfo[i].ParameterType != Args[i].GetType())
                                        
{
                                            same 
= false;
                                        }

                                    }

                                }

                                
if (same)
                                
{
                                    HereType 
= t;
                                    method 
= mInfo;
                                }

                            }

                        }


                        
if (method != null)
                        
{
                            
break;
                        }

                    }


                    
if (method != null)
                    
{
                        
break;
                    }

                }


                
if (method != null)
                
{
                    
break;
                }

            }


            
if (method == null)
            
{
                
//Log.LogException(typeof(Excute), "没有发现:" + FileName + "/" + MethodName, new Exception("没有发现:" + FileName + "/" + MethodName));
                return null;
            }



            
//ClassLibrary1.CTester

            
object ins = null;
            
if (!method.IsStatic)
            
{
                ins 
= a.CreateInstance(HereType.FullName);
            }


           
            
            
object RetObject = method.Invoke(ins, Args);
            
return RetObject;
        }




        
private string test5()
        
{
            
            
int now = System.Environment.TickCount;
            
for (int i = 0; i < 1000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    InvokeMehod(
@"F:\test\Reflection_Test\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll""test1"new object[] { });
                }

            }


            
string time = (System.Environment.TickCount - now).ToString();
            
return time;
        }


对 CTester 类实例化,为了加载程序集并反射
using System;
using System.Collections.Generic;
using System.Text;

namespace ClassLibrary1
{
    
//被测试类
    public class CTester
    
{
        
public CTester()
        
{
            a 
= 10;
        }


        
public void test1()
        
{
            a 
= (a - 0.0001* 1.0001;
        }

        
private double a;
        
public double geta() return a; }
    }

}




(附)主程序如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Collections;

//测试类
namespace ConsoleApplication2
{

    
public class CTester
    
{
        
public CTester()
        
{
            a 
= 10;
        }



        
public void test1()
        
{
            a 
= (a - 0.0001* 1.0001;
        }

        
private double a;
        
public double geta() return a; }
    }


    
class Program
    
{
        
private string test1()
        
{
            
int now = System.Environment.TickCount;

            
for (int i = 0; i < 1000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    CTester aTest 
= new CTester();
                    aTest.test1();

                }

            }


            
string time = (System.Environment.TickCount - now).ToString();
            
return time;
        }


        
static Hashtable table = new Hashtable();
        
private string test3()
        
{
            
int now = System.Environment.TickCount;

            
for (int i = 0; i < 1000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    Type theTest 
= null;
                    
//ContainsKey 确定 System.Collections.Hashtable 是否包含特定键
                    if (table.ContainsKey("ConsoleApplication2.CTester"))
                    
{
                        theTest 
= table["ConsoleApplication2.CTester"as Type;
                    }

                    
else
                    
{
                        
//Type theTest
                        theTest = Type.GetType("ConsoleApplication2.CTester");
                        
//Hashtable table
                        table.Add("ConsoleApplication2.CTester", theTest);
                    }

                    ConsoleApplication2.CTester theobj 
= theTest.InvokeMember(null, BindingFlags.CreateInstance
                        , 
nullnullnullas ConsoleApplication2.CTester;
                    theobj.test1();
                }

            }


            
string time = (System.Environment.TickCount - now).ToString();
            
return time;
        }


        
private string test2()
        
{
            
int now = System.Environment.TickCount;
            
for (int i = 0; i < 1000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    
//Type theTest = theTest = Type.GetType("ConsoleApplication2.CTester"); ;//

                    Type theTest 
= Type.GetType("ConsoleApplication2.CTester"); ;//


                    ConsoleApplication2.CTester theobj 
= theTest.InvokeMember(null, BindingFlags.CreateInstance
                        , 
nullnullnullas ConsoleApplication2.CTester;
                    theobj.test1();
                }

            }


            
string time = (System.Environment.TickCount - now).ToString();
            
return time;
        }


        
static object InvokeMehod(string FileName,
            
string MethodName,
            
object[] Args)
        
{
            Assembly a 
= Assembly.LoadFrom(FileName);


            MethodInfo method 
= null;
            Type HereType 
= null;


            
//在模块上进行反射
            foreach (Module m in a.GetModules())
            
{
                
//表示类型声明:类类型、接口类型、数组类型、值类型、枚举类型、类型参数、泛型类型定义,以及开放或封闭构造的泛型类型。
                foreach (Type t in m.GetTypes())
                
{
                    
//发现方法的属性 (Attribute) 并提供对方法元数据的访问。
                    foreach (MethodInfo mInfo in t.GetMethods())
                    
{
                        
if (mInfo.Name == MethodName)
                        
{
                            ParameterInfo[] pInfo 
= mInfo.GetParameters();
                            
if (pInfo.Length == Args.Length)
                            
{
                                
bool same = true;
                                
for (int i = 0; i < pInfo.Length; i++)
                                
{
                                    
if (Args[i] != null && pInfo[i].ParameterType != typeof(object)
                                        
&& pInfo[i].ParameterType != typeof(object[]))
                                    
{
                                        
if (pInfo[i].ParameterType != Args[i].GetType())
                                        
{
                                            same 
= false;
                                        }

                                    }

                                }

                                
if (same)
                                
{
                                    HereType 
= t;
                                    method 
= mInfo;
                                }

                            }

                        }


                        
if (method != null)
                        
{
                            
break;
                        }

                    }


                    
if (method != null)
                    
{
                        
break;
                    }

                }


                
if (method != null)
                
{
                    
break;
                }

            }


            
if (method == null)
            
{
                
//Log.LogException(typeof(Excute), "没有发现:" + FileName + "/" + MethodName, new Exception("没有发现:" + FileName + "/" + MethodName));
                return null;
            }



            
//ClassLibrary1.CTester

            
object ins = null;
            
if (!method.IsStatic)
            
{
                ins 
= a.CreateInstance(HereType.FullName);
            }


           
            
            
object RetObject = method.Invoke(ins, Args);
            
return RetObject;
        }




        
private string test5()
        
{
            
            
int now = System.Environment.TickCount;
            
for (int i = 0; i < 1000; i++)
            
{
                
for (int j = 0; j < 100; j++)
                
{
                    InvokeMehod(
@"F:\test\Reflection_Test\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll""test1"new object[] { });
                }

            }


            
string time = (System.Environment.TickCount - now).ToString();
            
return time;
        }





        
static void Main(string[] args)
        
{
            Program p 
= new Program();
            
string ticks = p.test1();
            Console.WriteLine(
"用编译器执行:" + ticks);
            
string t = p.test2();
            Console.WriteLine(
"用反射执行" + t);
            
string t1 = p.test3();
            Console.WriteLine(
"优化之后的反射:" + t1);
            
string t2 = p.test5();
            Console.WriteLine(
"加载程序集并反射:" + t2);
            
if (ticks.ToString() == "0")
            
{
                Console.WriteLine(
"反射/编译: 不在一个级别上面");
            }

            
else
            
{
                Console.WriteLine(
"反射/编译 =" + (Convert.ToInt32(t) / Convert.ToInt32(ticks)).ToString());
            }


            
if (ticks.ToString() == "0")
            
{
                Console.WriteLine(
"加载程序集并反射/编译: 不在一个级别上面");
            }

            
else
            
{
                Console.WriteLine(
"加载程序集并反射/编译 =" + (Convert.ToInt32(t2) / Convert.ToInt32(ticks)).ToString());
            }



            
//Console.WriteLine("加载程序集并反射/反射 =" + (Convert.ToInt32(t2) / Convert.ToInt32(t)).ToString());

            Console.Read();
        }

    }

}


posted @ 2007-02-08 15:45  jhtchina  阅读(1039)  评论(1)    收藏  举报