Question on Object Initialization

  • Thread starter Thread starter kit
  • Start date Start date
K

kit

Dear All

I have a question about object initialization in vb.net. In my program, an
instance "objABC" of object "ABC" is created and it has a method called
"method". The coding just like :

Dim objABC as ABC
objABC.method()

But i have an idea to assign the name of the instance and method
dynamically, just like :

Dim objectname As String
Dim methodname As String

Dim "objectname" as ABC
"objectname"."methodname"()

Is it possible to work like this ?

Thank you for your kind assistance to solve my problem.

Thanks
Kit
 
kit said:
Dear All

I have a question about object initialization in vb.net. In my program, an
instance "objABC" of object "ABC" is created and it has a method called
"method". The coding just like :

Dim objABC as ABC
objABC.method()

I'll just assume there's a new statement somewhere between those two,
otherwise it won't work. ^_~
But i have an idea to assign the name of the instance and method
dynamically, just like :

Dim objectname As String
Dim methodname As String

Dim "objectname" as ABC
"objectname"."methodname"()

The only way I can think to do the first one is to store all your objects in
a HashTable:
Dim MyObjects As New System.Collections.Hashtable()
MyObjects.Add(objectname, New ABC)

The second part can be accomplished using reflection:
Dim MyMethod As System.Reflection.MethodInfo = _
MyObjects("objectname").GetType().GetMethod(methodname)
MyMethod.Invoke(MyObjects("objectname"), Nothing)
 
Sven Groot said:
Dim MyMethod As System.Reflection.MethodInfo = _
MyObjects("objectname").GetType().GetMethod(methodname)
MyMethod.Invoke(MyObjects("objectname"), Nothing)

Er, obviously objectname shouldn't be in quotes here.
 
Dim objABC as ABC
objABC.method()

But i have an idea to assign the name of the instance and method
dynamically, just like :

Dim "objectname" as ABC
"objectname"."methodname"()

Yes, you can do this, but a full description is a little much for one post.
Take a look at the System.Reflection namespace, the CallByName function and
Delegates - that should get you started. Above all, Delegates are probably
the safest, and best way to go and CallByName would be the worst (depending
on circumstances).

However, you may want to reconsider your design because when questions like
this come up, it's usually a sign of a big design flaw. Don't get me wrong,
there are valid uses for binding and calling objects dynamically, but you
should know that you are basicly tossing the strong type system out the
window. As a result, you may loose the description in your exceptions (to
be replaced by some annoying generic message), have increased difficulty
with break points and debugging, and there will definitly be more than one
time (several in my case) when your code blows up, and you just burst into
tears.

=)

good luck,
jeremy
 
Back
Top