我正在编写一个项目,稍后将使用更多模块对其进行扩展,因此我希望尽可能多的代码是独立的,因此我使用各种方法来保存所有内容尽可能通用,不需要类型,类等的硬编码列表。
作为一个概念证明,我在课堂上提出了以下代码;
Public Class clsAddition
Public Function DoAction(Value1 As String, Value2 As String) As String
Dim dblTmpRet As Double
Dim strTmpRet As String = ""
If IsNumeric(Value1) = False Then strTmpRet += "Argument 'Value1' is not numeric. "
If IsNumeric(Value2) = False Then strTmpRet += "Argument 'Value2' is not numeric. "
If strTmpRet = "" Then
dblTmpRet = CDbl(Value1) + CDbl(Value2)
strTmpRet = CStr(dblTmpRet)
End If
Return strTmpRet
End Function
Private Function IsNumeric(Input As String) As Boolean
Dim blnTmpRet As Boolean
Try
Dim dblTest As Double = CDbl(Input)
blnTmpRet = True
Catch ex As Exception
blnTmpRet = False
End Try
Return blnTmpRet
End Function
Public Sub New()
MyBase.New()
End Sub
End Class
以下代码在windows窗体中;
Private objObjectClass As Object
Private Sub cmdCreateObject_Click(sender As Object, e As EventArgs) Handles cmdCreateObject.Click
Dim assem As Assembly = GetType(Form1).Assembly
Dim typChosen As Type
Try
typChosen = assem.GetType(Me.comObjectType.SelectedItem.ToString, True)
Catch ex As Exception
typChosen = Nothing
End Try
If Not IsNothing(typChosen) Then
'found it
objObjectClass = Activator.CreateInstance(typChosen, True)()
Else
'didn't find it
Throw New Exception("Unable to locate type in assembly")
End If
End Sub
问题是,在" Activator.CreateInstance(typChosen,True)()"行,抛出以下错误
未处理的类型' System.MissingMemberException' 发生在Microsoft.VisualBasic.dll附加信息:否 找到类型' clsAddition'
的默认成员
我的目标是能够创建类的实例,然后在它们上调用已知的名称函数。在这个例子中,我创建了另一个名为" Divide"的类,或另一个名为" Concatinate"等等,但是在实际程序中,这些类将执行非常不同的操作,具有不同的属性,方法等,使用这一个函数(" DoAction"在上面的示例中)共享语法和返回类型。
请帮忙!现在已经敲了一会儿这个!
TIA!
答案 0 :(得分:0)
根据Per Hans Passant的评论,这是由于下一行的额外括号;
Activator.CreateInstance(typChosen, True)()
将此更改为;
Activator.CreateInstance(typChosen, True)
解决了这个问题。