[英]How to call a COM Object by ProgID with Reflection in C#
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字段为null。 我认为这是正常的,对吧? 它已经运行了。 有谁知道它为什么扔它? 如果我将device声明为dynamic
,则说它不能在运行时绑定到空对象(基本上是同一件事)。
对第一答案的回答:我认为反射需要将变量作为对象数组。 是的,Unpark是用大写的U书写的。ProgID事情似乎无关紧要。
好吧,如果ProgID为null
,则不会设置它,因为您仅检查字符串是否为空。 我总是使用string.IsNullOrEmpty(s)
代替s == ""
。
检查一下:
好吧,由于这个答案,我想我终于明白了: https : //stackoverflow.com/a/3199919/258482 。 问题是您必须使用InvokeMember
对COM对象执行任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.