您的位置:首页 > 编程语言 > C#

C#的反射详解(二)

2007-09-22 00:50 507 查看
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;









内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: