vendredi 25 août 2017

Calling Class By Name or Select Case?

VB.NET, but C# would also do.

I have a MustInherit base class and 170 inherited classes based on that. Why so many? Because each inherited class does something different in Sub New(). The inherited types do not add any new properties, but do have different private fields. They simply process different sets of known variables differently. So think like this:

Public MustInherit Class Base
     Public Property Width
End Class

Public Class Child1
     Inherits Base
     Private z as Integer = 7
     Public Sub New(x as integer)
           Width = 20 * x * 7
     End Sub
End Class

Public Class Child170
     Inherits Base
     Private y as Integer = 4
     Public Sub New(x as integer)
           Width = 5 * x / y
     End Sub
End Class

In reality, what's in the Sub New is a ton of processing instructions based on what is sent in (e.g. X as Integer). Those processing instructions will work with a large number of private variables that sit in the inherited class.

Also, I'll know which child I need to create based on a string variable that is named the same thing like child1 or child170.

So, with so many inherited children, what's the best approach here (fastest, shortest amount to write, best performance, etc.)

Options:

  1. Use a Select Case to call and create one of 170 different classes, like:

    Dim b as Base Select Case childName Case "child1" b = New Child1(x) Case "child74" b = New Child74(x) Case "child103" b = New Child103(x) End Select

  2. Somehow reflect my call to create a generic one (pseudo as I don't know much about this):

    Dim b as Base = Activator.CreateInstance(Type.GetType("MyProjectName" & childName)) wherein "childName" is one of 170 children and then b.Process(x) - this assumes I use a routine called Process as I haven't seen any examples of sending values in a constructor in the CreateInstance thing.

  3. Something else?

Any help/advice/best practice would be welcome (except those that say "why do you need 170 thing? don't use 170 things").





Aucun commentaire:

Enregistrer un commentaire