class Device{
private object device;
public Device(string ProgID)
{
if (ProgID == "") ProgID = "ScopeSim.Telescope";
device = Activator.CreateInstance(Type.GetTypeFromProgID(ProgID));
Console.WriteLine("Connected");
}
public object Invoke(string Name, object[] args)
{
var v1 = device.GetType(); //this is a com object in debug
var v2 = v1.GetMethod(Name);
var v3 = v2.Invoke(device,args); //throws exception, v2 is null
return v3;
}
}
//somwhere else in another method in another class that has this in a field...
Console.WriteLine(new Device("").Invoke("A Method Name that is a string but is not known and could be anything, for testing, the name is 'Unpark'", object[] args));
这会抛出一个NullReferenceException
. Unpark 方法确实存在,但它没有返回类型,但它确实存在。此外,当它停止调试(异常)时,构造函数中的 ProgID 字段为空。我会认为这是正常的,对吧?它应该已经运行了。有谁知道它为什么会抛出它?如果我将设备声明为dynamic
,则表示它不能在运行时绑定到空对象(基本上是同一件事)。
对第一个答案的回应:我认为反射需要将变量作为对象数组。是的,Unpark 是用大写的 U 编写的。ProgID 的事情显然似乎无关紧要。