请我不知道我做错了,当我运行此代码,我得到一个异常:值不能为空....当我在调试模式下运行它,我看到"calculatorInstance"变量为空.请帮帮我.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace ReflectionWithLateBinding
{
public class Program
{
static void Main()
{
//load the current executing assembly
Assembly executingAssembly = Assembly.GetExecutingAssembly();
//load and instantiate the class dynamically at runtime - "Calculator class"
Type calculatorType = executingAssembly.GetType("ReflectionWithLateBinding.Calculator");
//Create an instance of the type --"Calculator class"
object calculatorInstance = Activator.CreateInstance(calculatorType);
//Get the info of the method to be executed in the class
MethodInfo sumArrayMethod = calculatorType.GetMethod("SumNumbers");
object[] arrayParams = new object[2];
arrayParams[0] = 5;
arrayParams[1] = 8;
int sum;
sum = (int)sumArrayMethod.Invoke(calculatorInstance, arrayParams);
Console.WriteLine("Sum = {0}", sum);
Console.ReadLine();
}
public class Calculator
{
public int SumNumbers(int input1, int input2)
{
return input1 + input2;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我很确定它实际上GetType是返回的方法null- 因为没有具有完全限定名称的类型ReflectionWithLateBinding.Calculator.你的Calculator班级嵌套在你的Program班级里.
它的调用Activator.CreateInstance是抛出一个异常,因此calculatorInstance永远不会进行赋值- 它不是变量的值null,而是它的声明语句(包括初始化程序)永远不会完成.
选项(不要两者兼得!):
Program类(即所以它直接声明的命名空间)GetType通话更改为executingAssembly.GetType("ReflectionWithLateBinding.Program+Calculator")