我不知道我做错了什么,当我运行此代码时,我得到一个异常:值不能为null。。。。当我在调试模式下运行它时,我看到"calculatorInstance"变量为null。请帮帮我。
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;
}
}
}
}
我很确定它实际上是返回null
的GetType
方法,因为没有完全限定名称为ReflectionWithLateBinding.Calculator
的类型。Calculator
类嵌套在Program
类中。
是对Activator.CreateInstance
的调用引发了异常,因此从未对calculatorInstance
进行赋值——这并不是因为变量的值为null
,而是因为它的声明语句(包括初始值设定项)从未完成。
选项(不要两者都做!):
- 移动该类,使其在
Program
类中为而不是(即,使其直接在命名空间中声明) - 将您的
GetType
呼叫更改为executingAssembly.GetType("ReflectionWithLateBinding.Program+Calculator")