类不能被嵌入。请使用适用的接口。

23

我正在使用WIA从扫描仪中捕获图像并将其显示在Windows窗体中。这是我正在使用的代码:

private void button2_Click(object sender, EventArgs e)
{
    const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
    CommonDialogClass wiaDiag = new CommonDialogClass();
    WIA.ImageFile wiaImage = null;

    wiaImage = wiaDiag.ShowAcquireImage(
            WiaDeviceType.UnspecifiedDeviceType,
            WiaImageIntent.GrayscaleIntent,
            WiaImageBias.MaximizeQuality,
            wiaFormatJPEG, true, true, false);

    WIA.Vector vector = wiaImage.FileData;

    Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));
    i.Save(@"D:\prueba1.jpeg");
}
当尝试运行这个小测试时,我收到了以下错误:
Interop类型“WIA.CommonDialogClass”无法嵌入。请改用适当的接口。
以及这个错误提示:
“WIA.CommonDialogClass”不包含“ShowAcquireImage”的定义,并且没有扩展方法“ShowAcquireImage”接受类型为“WIA.CommonDialogClass”的第一个参数可以被找到(您是否缺少使用指令或程序集引用?)
我猜测第二个错误是由于第一个错误导致的,对吗?
你有任何修复建议吗?

我发现CommonDialogClass适用于.NET 3.5,而您遇到的问题是在以后版本中引入的。 - Kyle Delaney
3个回答

26

第二个错误是由第一个错误引起的。嵌入互操作类型功能仅支持嵌入接口,而不是类。除了将该选项设置为 WIA 引用的 False 并部署互操作库之外,您还可以通过以下方式进行修复:

 WIA.CommonDialog wiaDiag = new WIA.CommonDialog();

虽然不直观,但使用new操作符创建COM接口是允许的。您需要在命名空间名称前加前缀,因为CommonDialog与Winforms CommonDialog类存在歧义。


1
太棒了!它几乎像一个“动态”类一样工作,你不会得到任何操作的智能感知,但它实际上表现如预期。谢谢朋友! - Mike Perrenoud

9

发生此错误是因为新项目中引用的TestStand API Interop程序集的嵌入互操作类型属性默认值为true。要解决此错误,请按照以下步骤更改嵌入互操作类型属性的值为False:

http://digital.ni.com/public.nsf/allkb/4EA929B78B5718238625789D0071F307

Select the TestStand Interop Assembly reference in the references section of your project in the Solution Explorer.
Find the Embed Interop Types property in the Property Browser, and change the value to False

相关链接: 知识库595FQJPI:我能否在TestStand中使用Visual Studio 2010并调用.NET Framework 4.0代码模块?


5

简单来说,您只需将错误的程序集选择到“解决方案资源管理器/引用”中。然后,按下Alt-Enter(属性),找到“嵌入互操作类型”并将其值设置为“False”,如果它是True的话。

Brgs!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接