简体   繁体   English

使用COM-Interop将数组从JS返回到C#

[英]Returning an array from JS to C# with COM-Interop

I'm returning some data from my JavaScript code to my C# code via COM Interop and the WebBrowser WPF control. 我通过COM Interop和WebBrowser WPF控件将我的JavaScript代码中的一些数据返回到我的C#代码。 I have successfully returned the data which looks like this in Javascript: 我已成功返回Javascript中的数据:

var result = new Array(); 
result[0] = cbCamera.selectedItem; 
result[1] = cbMicrophone.selectedItem;

Now I have the object result in C# which looks like this: 现在我将对象结果放在C#中,如下所示:

result.GetType(); 
{Name = "__ComObject" FullName = "System.__ComObject"}

How can I get the javascript strings contained in this array which is in this ComObject? 如何获取此ComObject中此数组中包含的javascript字符串?

To find the underlaying type of the object contained in the rutime callable wrapper (System.__ComObject) you would use refection. 要查找rutime可调用包装器(System .__ ComObject)中包含的对象的底层类型,您将使用refection。 You would then be able to create or cast to a managed type from this information. 然后,您就可以从此信息创建或转换为托管类型。

For example; 例如;

string type = (string)result.GetType().InvokeMember("getType",
BindingFlags.InvokeMethod, null, result, null);

Alternatively you could use invokeMember to retrieve the values. 或者,您可以使用invokeMember来检索值。 For example you could invoke the valueOf method to convert the array to the most meaningful primitive values possible or toString to covert the array to a csv string. 例如,您可以调用valueOf方法将数组转换为可能的最有意义的原始值,或者调用toString将数组转换为csv字符串。

string result = (string)result.GetType().InvokeMember("toString",
BindingFlags.InvokeMethod, null, result, null);
string[] jsArray = result.Split(',');
// c# jsArray[n] = js result[n] 

EDIT: A third way to do this in c# 4.0 is to use the new dynamic type. 编辑:在c#4.0中执行此操作的第三种方法是使用新的动态类型。 The dynamic type makes it really easy to make late-bound calls on COM objects. 动态类型使得在COM对象上进行后期绑定调用变得非常容易。

string csv = ((dynamic)result).toString();

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

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