c# - Reflection error: "parameter type mismatch" -
i trying understand reflection in c# , trying following code work. first method (getusername) works second method (addgivennumbers) giving me exception error of "parameter type mismatch". created class library 2 methods , trying use reflection in main console application.
class library code:
namespace classlibrarydelete { public class class1 { public string getusername(string account) { return "my name " + account; } public int addgivennumbers(int num1, int num2) { return num1 + num2; } } }
code in main console application:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using system.reflection; namespace consoleapplicationdelete_reflection { class program { static void main(string[] args) { assembly assemblyinstance = assembly.loadfrom(@"c:\users\xyz\desktop\debug\classlibrarydelete.dll"); type class1type = assemblyinstance.gettype("classlibrarydelete.class1"); object class1instance = activator.createinstance(class1type); methodinfo getmethodfullname = class1type.getmethod("getusername"); string[] parameter = new string[1]; parameter[0] = "john doe"; string username = (string)getmethodfullname.invoke(class1instance, parameter); console.writeline("user name = {0}", username); assembly assemblyinstance2 = assembly.loadfrom(@"c:\users\xyz\desktop\debug\classlibrarydelete.dll"); type classtype2 = assemblyinstance.gettype("classlibrarydelete.class1"); object class1instance2 = activator.createinstance(classtype2); methodinfo getmethodfullname2 = classtype2.getmethod("addgivennumbers"); //object[] parameters = new object[2]; //parameters[0] = 8; //parameters[1] = 4; object[] args2 = new object[] { 1, 2 }; object result = getmethodfullname.invoke(class1instance2, args2); console.writeline("sum of 2 numbers {0}", result); console.readline(); } } }
you have typo
object result = getmethodfullname.invoke(class1instance2, args2);
you should have been targeting getmethodfullname2
, otherwise you're trying execute first function (which takes 1 argument) 2 arguments.
working example: http://rextester.com/wbfyb30834
Comments
Post a Comment