简体   繁体   中英

Using a method whose name is stored in a string

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")

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM