[转载]反射技术

下面是反射技术的示例,我们可以在程序去得时动态实例化对象,获得对象的属性,并调用对象的方法。
using System;
using System.Collections.Generic;
using System.Text;
 
namespace ReflectionDemo
{
    public class HelloWorld
    {
        private string strName = null;
        public HelloWorld(string name)
        {
            strName = name;
        }
        public HelloWorld()
        {
        }
        public string Name
        {
            get
            {
                return strName;
            }
        }
        public void SayHello()
        {
            if (strName == null)
            {
                System.Console.WriteLine("Hello World");
            }
            else
            {
                System.Console.WriteLine("Hello World,"+strName);
            }
        }
 
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
 
namespace ReflectionDemo
{
        class Program
        {
            static void Main(string[] args)
            {
                System.Console.WriteLine("列出程序集中的所有类型");
                Assembly a = Assembly.LoadFrom ("ReflectionDemo.exe");
                Type[] mytypes = a.GetTypes( );
 
                foreach (Type t in mytypes)
                {
                  System.Console.WriteLine ( t.Name );
                }
                System.Console.ReadLine ( );
 
                System.Console.WriteLine ("列出HellWord中的所有方法" );
                Type ht = typeof(HelloWorld);
                MethodInfo[] mif = ht.GetMethods();
                foreach(MethodInfo mf in mif)
                {
                  System.Console.WriteLine(mf.Name);
                }
                System.Console.ReadLine();
 
                System.Console.WriteLine("实例化HelloWorld,并调用SayHello方法");
                Object obj = Activator.CreateInstance(ht); //调用无参数构造函数
 
                string[] s = {"zhenlei"};
                Object objName = Activator.CreateInstance(ht, s); //调用参数构造函数
 
                //BindingFlags flags = (BindingFlags.NonPublic|BindingFlags.Public|BindingFlags.Static|BindingFlags.Instance|BindingFlags.DeclaredOnly);
                MethodInfo msayhello = ht.GetMethod("SayHello");
                msayhello.Invoke(obj,null);
                msayhello.Invoke(objName,null);
                System.Console.ReadLine();
 
                }
            }
    }
 
----第二部分----
2。动态添加和使用类型

反射提供了由语言编译器(例如 Microsoft Visual Basic .NET 和 JScript)用来实现隐式晚期绑定的基础结构。绑定是查找与唯一指定的类型相对应的声明(即实现)的过程。由于此过程在运行时而不是在编译时发生,所以称作晚期绑定。Visual Basic .NET 允许您在代码中使用隐式的晚期绑定;Visual Basic 编译器将调用一个帮助器方法,该方法使用反射来获取对象类型。传递给帮助器方法的参数有助于在运行时调用正确的方法。这些参数包括:对其调用方法的实例(对象),被调用方法的名称(字符串),以及传递给被调用方法的参数(对象数组)。

 
以下示例是动态调用动态链接库中的GetDataSet方法,该方法需要参数string userID

 

 
 
3. 访问自定义属性
       访问自定义属性和动态添加和使用类型一样.
 /// <summary>
        
/// 执行公式的运算
        
/// </summary>
        
/// <param name="value">需要计算的原始值</param>
        
/// <param name="assessment">考核名称</param>
        
/// <returns></returns>

        public float ExeExpression(string assessment, params object[] values)
        
{

            
string expression = this.GetExpression(assessment);
            
//从当前应用程序加载此dll  
            string path = "";
            
if (System.Environment.CurrentDirectory + @"" == AppDomain.CurrentDomain.BaseDirectory)//Windows应用程序则相等
            {
                path 
= AppDomain.CurrentDomain.BaseDirectory;
            }

            
else
            
{
                path 
= AppDomain.CurrentDomain.BaseDirectory + @"Bin";
            }

            
string dllPath = path + expression + ".dll";
            System.Reflection.Assembly assmble 
= System.Reflection.Assembly.LoadFile(dllPath);

            
string typeFullName = expression + ".ExpressionClass";
            Type tmpType 
= assmble.GetType(typeFullName);
            System.Reflection.MethodInfo tmpMethod 
= tmpType.GetMethod("ExeExpression");
            System.Reflection.PropertyInfo tmpProperty 
= tmpType.GetProperty("ConnectionString");

            
//创建对象,设置属性值,并调用方法
            object tmpobj = assmble.CreateInstance(typeFullName);
            tmpProperty.SetValue(tmpobj, connectionString, 
null);
            
float result = 0;
            result 
= (float)tmpMethod.Invoke(tmpobj, values);
            
return result;

        }
Assembly assembly; 
Type type; 

string dllPath = @"D: estPowerSpace.VCP.Utility.dll"
try 


     assembly 
= Assembly.LoadFile(dllPath); 
     type 
= assembly.GetType("PowerSpace.VCP.Utility.cMyString",true,true);//cMyResult 
}
 
catch(FileNotFoundException) 


Response.Write(
"Could not load Assembly: ""+ dllPath +"""); 

     Return 
null

}
 
catch(TypeLoadException) 



Response.Write(
"Could not load Type: "string"   from assembly: "" + dllPath + """); return null


}
 

MethodInfo method 
= type.GetMethod("TestInvoke"); 

object obj = Assembly.GetAssembly(type).CreateInstance("PowerSpace.VCP.Utility.GetDataSet"); 


object s = method.Invoke(obj,new object[]{"jiangli"}); 

DataSet ss 
= (DataSet)s; 

assembly 
= null
type 
= null
method 
=null
return ss; 


posted @ 2007-11-04 23:44  黑羽飘舞  阅读(221)  评论(0编辑  收藏  举报