How to create a new object instance from a Type

后端 未结 12 1737
孤城傲影
孤城傲影 2020-11-22 03:26

One may not always know the Type of an object at compile-time, but may need to create an instance of the Type.

How do you get a new objec

12条回答
  •  盖世英雄少女心
    2020-11-22 03:56

    I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)

    With generic method you can require that the type implements New().

    Public Function CloneObject(Of T As New)(ByVal src As T) As T
        Dim result As T = Nothing
        Dim cloneable = TryCast(src, ICloneable)
        If cloneable IsNot Nothing Then
            result = cloneable.Clone()
        Else
            result = New T
            CopySimpleProperties(src, result, Nothing, "clone")
        End If
        Return result
    End Function
    

    With non-generic assume the type has a default constructor and catch an exception if it doesn't.

    Public Function CloneObject(ByVal src As Object) As Object
        Dim result As Object = Nothing
        Dim cloneable As ICloneable
        Try
            cloneable = TryCast(src, ICloneable)
            If cloneable IsNot Nothing Then
                result = cloneable.Clone()
            Else
                result = Activator.CreateInstance(src.GetType())
                CopySimpleProperties(src, result, Nothing, "clone")
            End If
        Catch ex As Exception
            Trace.WriteLine("!!! CloneObject(): " & ex.Message)
        End Try
        Return result
    End Function
    

提交回复
热议问题