我试图理解c#中的Reflection,我试图让以下代码工作。第一种方法(GetUserName)有效,但第二种方法(AddGivenNumbers)给我一个例外错误"参数类型不匹配"。 我用2个方法创建了一个类库,并尝试在主控制台应用程序中使用反射。
namespace ClassLibraryDELETE
{
public class Class1
{
public string GetUserName(string account)
{
return "My name is " + account;
}
public int AddGivenNumbers(int num1, int num2)
{
return num1 + num2;
}
}
}
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 the two numbers is {0}", result);
Console.ReadLine();
}
}
}
答案 0 :(得分:2)
你有一个错字
object result = getMethodFullName.Invoke(class1Instance2, args2);
你应该定位getMethodFullName2
,否则你试图用2个参数执行第一个函数(带1个参数)。