Incubus
Incubus

Reputation: 46

Instantiate many classes

In my current project, a circuit drawing program, I'm deriving many classes from the same base class.

Public MustInherit Class clsCompo

Public Class clsRelay Inherits clsCompo
Public Class clsResistor Inherits clsCompo

Each child class has a 'getIcon' function that provides the desired image of the component. These get loaded in a listview to be used in the drawing program.

Is there an easy way to instantiated these classes to be used? Is there another way than manually instantiating each class? And then adding the image to the listview: something like:

    Dim classes() As String = {"clsResistor", "clsRelay"}
    Dim c(1) As Object

    For Each cls As String In classes
        c(1) = New cls
        'add image to listview
    Next

I'm using .NET 3.5

Thanks

Upvotes: 0

Views: 72

Answers (2)

Heinzi
Heinzi

Reputation: 172220

If your classes have a parameterless constructor:

c(1) = Activator.CreateInstance(Type.GetType("MyNamespace." & cls))

Obviously, MyNamespace. should be replaced as appropriate.

Upvotes: 4

Victor Zakharov
Victor Zakharov

Reputation: 26424

You will need to use reflection and Activator.CreateInstance specifically to perform this trick. Going towards reflection path is dangerous, and usually brings more trouble than it gives benefits. In most cases there is a better way to design your application.

In your particular case, you could have a dictionary of icons, string to icon match, then just have a constructor of clsCompo specify the icon you want as a parameter. Unless you are using inheritance for something else, this should totally solve your problem, without the burden of using reflection.

Upvotes: 0

Related Questions