推薦:ASP.NET 2.0 里輸出文本格式流在用 ASP.NET 編程時,打開一個頁面一般是通過指定超鏈接地址,調用指定的頁面文件(.html、.aspx)等方法。但是,如果即將打開的頁面文件的內容是在程序中動態生成,或者是從數據庫的表里取出
用.net動態創建類的實例
看了網上很多關于DotNet動態創建類的實例的文章,我這里想總結一下,其實方法很簡單,就是用“Activator.CreateInstance”。但是這個方法需要待創建的類的Type作為參數,為了獲得該參數,可以利用[Assembly].GetType方法,這個方法只需要待創建的類的名稱(名稱字符串)就可以了,最后的問題就是要獲得這個類所在的程序集。如何獲得待創建的類所在程序集,那么就解決了這個問題。
其實,在獲得程序集這個問題上,可以有更簡單的辦法,以下是我的做法。
利用Microsoft.VisualBasic.VBCodeProvider(),如果是C#可以用CSharpCodeProvider(),將類文件編譯成為DLL文件,然后利用[Assembly].LoadFrom("DLL 的絕對路徑")加載該DLL。這樣我們可以避免在那些創建DLL和Type的復雜代碼。我告訴我的項目組成員這個例子后,強調要打開思路,Simple is perfect,凡事都盡量找簡便的方法來實現,客戶永遠不會為我們那些復雜的代碼多花一分錢。
1.執行編譯任務的方法:
Public Shared Function CompileExecutable()Function CompileExecutable(ByVal sourceName As String, ByVal DLLPath As String, ByRef ReturnDLLName As String) As Boolean
Dim sourceFile As FileInfo = New FileInfo(sourceName)
Dim provider As CodeDomProvider = Nothing
Dim compileOk As Boolean = False
' 根據原文件的擴展名選擇code provider
If sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) = ".CS" Then
provider = New Microsoft.CSharp.CSharpCodeProvider()
ElseIf sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) = ".VB" Then
provider = New Microsoft.VisualBasic.VBCodeProvider()
Else
Console.WriteLine("原文件必須包含 .cs 或 .vb 擴展名")
End If
If Not provider Is Nothing Then
' 構造DLL文件的全路徑
Dim dllName As String = String.Format("{0}/{1}.dll", _
DLLPath, _
sourceFile.Name.Replace(".", "_"))
ReturnDLLName = dllName
Dim cp As CompilerParameters = New CompilerParameters()
' 設置編譯控制參數
cp.GenerateExecutable = False '生成DLL,如果是True則生成exe文件
cp.OutputAssembly = dllName
cp.GenerateInMemory = False
cp.TreatWarningsAsErrors = False
' 調用編譯方法將原代碼文件編譯成DLL
Dim cr As CompilerResults = provider.CompileAssemblyFromFile(cp, _
sourceName)
If cr.Errors.Count > 0 Then
' 顯示編譯錯誤
Console.WriteLine("編譯錯誤 {0} 編譯成 {1}", _
sourceName, cr.PathToAssembly)
Dim ce As CompilerError
For Each ce In cr.Errors
Console.WriteLine(" {0}", ce.ToString())
Console.WriteLine()
Next ce
Else
' 顯示編譯成功的消息
Console.WriteLine("原文件 {0} 編譯成 {1} 成功完成.", _
sourceName, cr.PathToAssembly)
End If
' 返回編譯結果
If cr.Errors.Count > 0 Then
compileOk = False
Else
compileOk = True
End If
End If
Return compileOk
End Function
2.編譯DLL,并動態創建類的實例。(這里類的原文件是Class1.vb文件,放在WebSite的App_Code文件夾中了,實際使用時可以放在任意物理位置。)
Dim strSourceFileName As String = Server.MapPath("~/App_Code/Class1.vb") '類文件的全路徑
Dim strDllPath As String = Server.MapPath("~/App_Code") '編譯后的DLL文件存放的位置
Dim strDllName As String = "" 'DLL的全路徑(返回值)
CompileExecutable(strSourceFileName, strDllPath, strDllName) '編譯原文件為DLL文件
Dim a As [Assembly] = [Assembly].LoadFrom(strDllName) '加載DLL
Dim myType As System.Type = a.GetType("Class1") '獲得Class1的Type
Dim obj As Object = Activator.CreateInstance(myType) '獲得Class1的實例
3.Class1.vb原文件
Public Class Class1Class Class1
Public i As Integer
End Class
分享:從XML文件中讀取數據綁定到DropDownList1 、綁定DropDownList: 以下為引用的內容:ddl_language.DataSource = createDataSource(); ddl_language.DataTextField = "languageText
新聞熱點
疑難解答
圖片精選