简体   繁体   English

无法将对象...转换为类型

[英]Unable to cast object … to type

Visual Studio 2008 (C#) created the Interop for my COM objects. Visual Studio 2008(C#)为我的COM对象创建了Interop。 The main objects which I am using are: OPCHDAServerClass , IOPCHDAItems , and OPCHDAItem . 我使用的主要对象是: OPCHDAServerClassIOPCHDAItemsOPCHDAItem The code is: 代码是:

OPCHDAServerClass server = new OPCHDAServerClass();
server.Connect("OPC.PHDServerHDA.1");
OPCHDAItem item = server.OPCHDAItems.AddItem("MyItem",1);

In the third line the AddItem method should return an OPCHDAItem . 在第三行中, AddItem方法应返回OPCHDAItem The interop definition for AddItem is: AddItem的互操作定义是:

[DispId(1610743813)]
OPCHDAItem AddItem(string ItemID, int ClientHandle);

The exception that I get is: 我得到的例外是:

Unable to cast object of type 'OPCHDAServerClass' to type 'IOPCHDAItems'. 无法将“OPCHDAServerClass”类型的对象强制转换为“IOPCHDAItems”类型。

I do not understand why I am getting this error message. 我不明白为什么我收到此错误消息。 server.OPCHDAItems implements IOPCHDAItems . server.OPCHDAItems实现IOPCHDAItems I do not know why server ( OPCHDAServerClass ) is being cast to IOPCHDAItems ? 我不知道为什么服务器( OPCHDAServerClass )被IOPCHDAItemsIOPCHDAItems

I did initial prototyping in python which worked fine so I know that the COM components are functional. 我在python中进行了初始原型设计工作正常,所以我知道COM组件是有用的。 This is the python code: 这是python代码:

server = win32com.client.dynamic.Dispatch("Uniformance.OPCHDA.Automation.1")
server.Connect("OPC.PHDServerHDA.1")
item = server.OPCHDAItems.AddItem("MyItem", 1)

Has anyone seen a similar issue and know of a work around? 有没有人看过类似的问题并知道一项工作?

Looks like the declared type of property OPCHDAItems is not IOPCHDAItems - it's OPCHDAServerClass . 看起来声明的属性类型OPCHDAItems不是IOPCHDAItems - 它是OPCHDAServerClass C# is a statically typed language - it won't typecast COM interfaces unless explicitly told to, and it won't go for the IDispatch unless told to. C#是一种静态类型语言 - 除非明确告知,否则不会对COM接口进行类型转换,除非告知,否则它不会用于IDispatch。 Rephrase like this: 改写如下:

server.Connect("MyServerName");
OPCHDAItem item = (server.OPCHDAItems as IOPCHDAItems).AddItem("MyItem",1);

EDIT: try this first: 编辑:先试试这个:

IOPCHDAItems Items = server.OPCHDAItems;

Still the same error? 还是一样的错误? How about 怎么样

IOPCHDAItems Items = server.OPCHDAItems as IOPCHDAItems;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM