0

I am trying to execute a method whose name is stored in a string ... for example

dim a as integer = warehouse.getTotalCount("item1")    'a is now equal to 100

but what i want to do is as so..

dim item1 as string = "item1"    
dim fctn = "warehouse.getTotalCount("+item1+")"
dim a as integer = run(fctn)   'and here a should be equal to 100

I have been trying to figure this out for some time now...

The functions may be coming from several different classes and I want to run the fully qualified name. How would I do this without using a case select?

EDIT: I am having trouble with

Type.GetType("warehouse") 

or

Type.GetType("fctn")
1
  • 2
    Read about Reflection. Commented Apr 9, 2014 at 12:50

1 Answer 1

2

This was taken from MethodBase.Invoke and should give you a general idea of how to do it, it's in C# but is easily convertable:

Type magicType = Type.GetType("MagicClass");
ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
object magicClassObject = magicConstructor.Invoke(new object[]{});

// Get the ItsMagic method and invoke with a parameter value of 100

MethodInfo magicMethod = magicType.GetMethod("ItsMagic");
object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});

Try something like this:

Dim myMethod = wareHouse.GetType().GetMethod("getTotalCount")
Dim res = myMethod.Invoke(wareHouse, New Object() {100})
Sign up to request clarification or add additional context in comments.

10 Comments

Although it's copied from MSDN, it would be helpful you also showed how magicType and magicClassObject were created
@freefaller added more detail.
i am having trouble with Type.GetType("warehouse") or Type.GetType("fctn")
if warehouse is the instatiated object try this: dim myMethod = warehouse.GetType().GetMethod("getTotalCount") Dim result = myMethod.Invoke(warehouse, New Object(){100})
no i never initalized the object... again thank you very much... sorry for the rookie mistake..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.