Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
CreateObject Equivalent
Message
Information générale
Forum:
ASP.NET
Catégorie:
Formulaires
Divers
Thread ID:
00635294
Message ID:
00636281
Vues:
16
PMFJI but I was catching up on e-mail and found this VB mailing list info I got that you might find useful:

--------------------------------------------------------

VB.NET WATCHER: CREATING OBJECTS DYNAMICALLY
by Francesco Balena (fbalena@vb2themax.com)
Excerpt from Chapter 15 of "Programming Microsoft Visual Basic .NET"
(Microsoft Press - release date: first quarter of 2002)

The last reflection feature to be examined lets you dynamically create an object on the fly if you have its class name. This is the Visual Basic .NET counterpart of the CreateObject function. You can choose from two ways to create a .NET object in this fashion: by using the CreateInstance method of the System.Activator class or by invoking the one of the type's constructor methods.

If the type has a parameterless constructor, creating an instance is trivial:
Sub TestObjectCreation()
    ' Next statement assumes that the Person class is defined in
    ' an assembly named "ReflectionDemo".
    Dim ty As Type = Type.GetType("ReflectionDemo.Person")
    Dim o As Object = Activator.CreateInstance(ty)
    ' Prove that we created a Person.
    Console.WriteLine("A {0} object has been created", o.GetType.Name)
End Sub
If you want to call a constructor that takes one or more parameters, you must prepare an array of values:
Sub TestObjectCreation2()
    Dim ty As Type = Type.GetType("ReflectionDemo.Person")
    ' Use the constructor that takes two arguments.
    Dim params() As Object = {"Joe", "Doe"}
    ' Call the constructor that matches the parameter signature.
    Dim o As Object = System.Activator.CreateInstance(ty, params)
End Sub
Creating an object through its constructor method is a bit more convoluted, but I'm reporting this technique here for the sake of completeness:
Sub TestObjectCreation3()
    Dim ty As Type = Type.GetType("ReflectionDemo.Person")
    ' Prepare the argument signature as an array of types (2 strings).
    Dim types() As Type = {GetType(System.String), GetType(System.String)}
    ' Get a reference to the correct constructor.
    Dim ci As ConstructorInfo = ty.GetConstructor(types)
    ' Prepare the parameters.
    Dim params() As Object = {"Joe", "Doe"}
    ' Invoke the constructor and assign the result to a variable.
    Dim o As Object = ci.Invoke(params)
End Sub
-----------------------------------------------------------------------

HTH,

>Thanks for the help.
>
>Where did you find good info on the Reflection class ?
>
>Thanks
>Rodman
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform