C#的反射技術詳解(二)
2。動態新增和使用型別
反射提供了由語言編譯器(例如 Microsoft Visual Basic .NET 和 JScript)用來實現隱式晚期繫結的基礎結構。繫結是查詢與唯一指定的型別相對應的宣告(即實現)的過程。由於此過程在執行時而不是在編譯時發生,所以稱作晚期繫結。Visual Basic .NET 允許您在程式碼中使用隱式的晚期繫結;Visual Basic 編譯器將呼叫一個幫助器方法,該方法使用反射來獲取物件型別。傳遞給幫助器方法的引數有助於在執行時呼叫正確的方法。這些引數包括:對其呼叫方法的例項(物件),被呼叫方法的名稱(字串),以及傳遞給被呼叫方法的引數(物件陣列)。
以下示例是動態呼叫動態連結庫中的
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
DataSet ss = (DataSet)s;
assembly = null;
type = null;
method =null;
return ss;
3. 訪問自定義屬性
訪問自定義屬性和動態新增和使用型別一樣.