摘要:動態載入類別
小弟今天看到 Allen大大寫的一篇文章
換個方式來講 interface / OO
www.allenkuo.com/GenericArticle/view437.aspx
前面我還寫的出來,只是後面動態的還真的沒有實做過,我通常都是先轉型再使用
想說有空就來寫寫看,以下是我實做的過程,如果有錯請大大們指導,謝謝:
首先寫簡單類別:
''' 介面
''' </summary>
''' <remarks></remarks>
Public Interface ISend
Function Send(ByVal memberID As String, ByVal message As String) As String
End Interface
''' <summary>
''' 實做ISend介面
''' </summary>
''' <remarks>手機簡訊類別</remarks>
Public Class clsMobile
Implements clsSend.ISend
Public Function Send(ByVal memberID As String, ByVal message As String) As String Implements ISend.Send
Dim recStr As String = ""
recStr = String.Format("這是手機傳簡訊的類別:帳號 {0} 訊息內容 {1}", memberID, message)
Return recStr
End Function
End Class
''' <summary>
''' 實做ISend介面
''' </summary>
''' <remarks>Mail類別</remarks>
Public Class clsMail
Implements clsSend.ISend
Public Function Send(ByVal memberID As String, ByVal message As String) As String Implements ISend.Send
Dim recStr As String = ""
recStr = String.Format("這是電子郵件類別:帳號 {0} 郵件內容 {1}", memberID, message)
Return recStr
End Function
End Class
App.config 增加以下設定(預設為手機簡訊):
<add key="objSend" value="clsSend"/>
<add key="clsSend" value="clsSend.clsMobile"/>
<!--郵寄類別 add key="clsSend" value="clsSend.clsMobile"/-->
</appSettings>
寫一個簡單winForm,放兩個textbox 一個為 使用者ID 一個為 傳送訊息內容
程式碼如下:
Imports System.Reflection
Public Class Form
''' <summary>
''' 讀取Config的設定決定要傳那一個類別
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Shared Function getSendObj() As ISend
Dim a As Assembly
Dim SendType As Type
Dim obj As Object
Try
'讀取組件的名稱
a = Assembly.Load(System.Configuration.ConfigurationManager.AppSettings.Item("objSend"))
'取得類別的名稱,預設為手機,如果要改成Mail直接改app.config的設定
SendType = a.GetType(System.Configuration.ConfigurationManager.AppSettings.Item("clsSend"))
obj = Activator.CreateInstance(SendType)
Return obj
Catch ex As Exception
MsgBox("應用程式讀取錯誤,請通知資訊人員。")
End
End Try
End Function
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Dim obj As ISend
obj = getSendObj()
MsgBox(obj.Send(Me.txtMemberID.Text, Me.txtMsg.Text))
End Sub
End Class