-2

I want to take a string like "driverLib.GetTotalRecordCount(\"name_of_table\")" and run it like a function call.

I followed the instructions from this post:

Calling a function from a string in C#

but I get an error saying the function doesn't exist in MySQLLib.

Code:

MySQLLib driverLib = new MySQLLib();

string funcName = "driverLib.GetTotalRecordCount";
string userParam = "\"name_of_table\"";

// Code from the link 
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(funcName);
theMethod.Invoke(this, userParam);
burntchowmein
  • 474
  • 1
  • 4
  • 16
  • Searching for „.net expression evaluator“ or something like that on google. – Uwe Keim Jun 29 '20 at 18:15
  • You're trying to invoke the method on `MySQLLib`. Are you sure that method is available in `MySQLLib`? – CodingYoshi Jun 29 '20 at 18:15
  • This line `Console.WriteLine(funcCall) // driverLib.GetTable1Data("name_of_table", ref lists)` cannot print what you're showing in the comments either. – CodingYoshi Jun 29 '20 at 18:18
  • You are referring to a class "driverlib" defined as a property in MySQLLib ? Why do you not use typeof(MySLLib.drivelib) ? why is the "driverlib." prefix needed in the first parameter.. ? – Goodies Jun 29 '20 at 18:22
  • You need to use the method name, you already have an instance of the type information, so calling a method doesn't require you to qualify the method with the type name, have you tried with just the method name? See the examples here https://learn.microsoft.com/en-us/dotnet/api/system.type.invokemember (look at `ToString`). As @codingyoshi says, there's a reference to `driverLib` but what is that? It's not referenced anywhere in your code and shouldn't be. – Charleh Jun 29 '20 at 18:29
  • @Charleh I have added the class declaration of MySQLLib in my code. driverLib is the name of the object. – burntchowmein Jun 29 '20 at 18:50
  • 1
    You don't need the name of the object, you created a new instance of the object when you used `Activator.CreateInstance` and stored the created object reference in the `obj` variable. If you want to call the method on `driverLib` you need to pass it in `InvokeMember` in the place of `obj`. `InvokeMember` does not know anything about the context so it doesn't know what `driverLib` is. You have followed a tutorial without understanding it and that's your issue. – Charleh Jun 29 '20 at 20:33

1 Answers1

1

Did you go through reflection tutorial? Check this blog: https://www.infoworld.com/article/3027240/how-to-work-with-reflection-in-c.html

What you could do is print all method's name of your MySQLLib and debug it:

Type type = typeof(MySQLLib);

MethodInfo[] methodInfo = type.GetMethods();

foreach(var method in methodInfo)
{
    Console.Writeline(method.Name);
}
Shawn L
  • 64
  • 1
  • 8