mercredi 24 janvier 2018

No default member found for type '' when using Activator.Instance - VB.NET

I'm writing a project where this will be extended with further modules later on, and as such i want as much of the code as possible to be independent, so i'm using various methods to keep everything as generic as possible, and not require hard-coding lists of types, classes etc.

As a Proof of concept, I've come up with the following code in a class;

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

And the following code in a windows form;

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

The issue is, that on the "Activator.CreateInstance(typChosen, True)()" line, the following error is thrown

An unhandled exception of type 'System.MissingMemberException' occurred in Microsoft.VisualBasic.dll Additional information: No default member found for type 'clsAddition'.

The aim is for me to be able to create instances of classes, then call a known name function on them. In this example, I'd create another class called "Divide", or another one that was called "Concatinate" etc, however in the real program these classes will all perform very different actions, have different properties, methods etc, with this one function ("DoAction" in the above example) sharing a syntax and return type.

Please help! been banging my head on this for a while now!

TIA!





Aucun commentaire:

Enregistrer un commentaire