简体   繁体   English

在C#中使用ActiveX

[英]Use ActiveX in C#

I have a javascript code like this: 我有一个像这样的JavaScript代码:

  o = new ActiveXObject("ASDFsome.Application");
  utilites = WScript.CreateObject("ASDF.Utilites.UTF.Converter")
  utilites.Convert(outFile, xmlProp.xml)

Now I want to rewrite it in C# code. 现在我想用C#代码重写它。 How should I use ActiveXObject in Net? 我该如何在Net中使用ActiveXObject?

This is in no small part why the dynamic keyword was added to C# version 4: 这在很大程度上归功于为C#版本4添加了动态关键字的原因:

dynamic utilites = Activator.CreateInstance(Type.GetTypeFromProgID("ASDF.Utilites.UTF.Converter"));
utilites.Convert(outFile, xmlProp.xml);

If you're stuck on an earlier version then using a VB.NET class library is the best approach. 如果你坚持使用早期版本,那么使用VB.NET类库是最好的方法。 It directly supports the CreateObject() function as used in your scripting code. 它直接支持脚本代码中使用的CreateObject()函数。

Last but not least, unlike the scripting language you've been using, both C# and VB.NET support early binding. 最后但并非最不重要的是,与您一直使用的脚本语言不同,C#和VB.NET都支持早期绑定。 That starts by adding a reference to the type library, Project + Add Reference and use either the COM tab or the Browse tab to pick the .tlb or .dll file that contains the type library. 首先添加对类型库的引用,Project + Add Reference,然后使用COM选项卡或Browse选项卡来选择包含类型库的.tlb或.dll文件。 You might not have one if the component was designed to be only ever used from late binding scripting languages. 如果组件设计为仅使用后期绑定脚本语言,则可能没有。 We can't otherwise help you find the proper type library, the vendor or author would know. 我们无法帮助您找到合适的类型库,供应商或作者会知道。

Really last but not least, this smells like a utility that knows how to read a utf-8 encoded XML file. 真的最后但并非最不重要,这闻起来像一个知道如何读取utf-8编码的XML文件的实用程序。 That's already really well supported in .NET with the System.Xml namespace. 使用System.Xml命名空间在.NET中已经得到了很好的支持。

One possibility is to use Reflection: 一种可能性是使用反射:

var utilitiesType = Type.GetTypeFromProgID("ASDF.Utilites.UTF.Converter");
var instance = Activator.CreateInstance(utilitiesType);
utilitiesType.InvokeMember(
    "Convert", 
    BindingFlags.InvokeMethod | BindingFlags.Public, 
    null, 
    instance, 
    new[] { "outputFile", "xmlProp.xml" }
);

Another possibility is to generate a strongly typed proxy for the COM object. 另一种可能性是为COM对象生成强类型代理。 Right click on your project, Add Reference -> COM tab -> Select the COM object in the list or load it from its DLL. 右键单击您的项目,添加引用 - > COM选项卡 - >在列表中选择COM对象或从其DLL加载它。 Visual Studio will then generate a strongly typed wrapped assembly for this COM object and automatically add it as reference. 然后,Visual Studio将为此COM对象生成强类型包装程序集,并自动将其添加为引用。 Next you could work with the COM object directly and by keeping its strong typing. 接下来,您可以直接使用COM对象并保持其强类型。

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

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