2。动态添加和使用类型
反射提供了由语言编译器(例如 Microsoft Visual Basic .NET 和 JScript)用来实现隐式晚期绑定的基础结构。绑定是查找与唯一指定的类型相对应的声明(即实现)的过程。由于此过程在运行时而不是在编译时发生,所以称作晚期绑定。Visual Basic .NET 允许您在代码中使用隐式的晚期绑定;Visual Basic 编译器将调用一个帮助器方法,该方法使用反射来获取对象类型。传递给帮助器方法的参数有助于在运行时调用正确的方法。这些参数包括:对其调用方法的实例(对象),被调用方法的名称(字符串),以及传递给被调用方法的参数(对象数组)。
以下示例是动态调用动态链接库中的GetDataSet方法,该方法需要参数string userID
Assembly assembly;
Type type;
string dllPath = @"D:/test/PowerSpace.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/" /n 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;
3. 访问自定义属性
访问自定义属性和动态添加和使用类型一样.
怎么样?反射难吗?呵呵,还是去研究研究吧。有事儿联系我:mailto:jljkyh@163.com