【问题标题】:c# COM Objects issuec# COM 对象问题
【发布时间】:2012-01-17 16:33:47
【问题描述】:

背景

我正在 Visual Studio 2010 中使用 C# 开发交易 ActiveX API。由于它是一个 ActiveX API,我只是添加了 ActiveX 作为我的参考。 api 提供了三组东西:您可以用来调用 API 的方法、API 用来为您更新信息的事件以及一些所谓的 ActiveX COM 对象。

问题

我在这里问了一个相关的问题:C# boolean int conversion issue 最后查看异常已经抛出,我知道是关于强制转换的。下面是异常的描述:

*System.InvalidCastException was unhandled Message=Unable to cast object of type  
InteractiveBrokersTradingSystem.Forex' to type 'TWSLib.IContract'.

*

这是我对外汇类的定义:

namespace InteractiveBrokersTradingSystem
{
  class Forex:TWSLib.IContract
  {


    public int conId { get; set; }
    public string symbol { get; set; }
    public string secType { get; set; }
    public string expiry { get; set; }
    public double strike { get; set; }
    public string right { get; set; }
    public string multiplier { get; set; }
    public string exchange { get; set; }
    public string primaryExchange { get; set; }
    public string currency { get; set; }
    public string localSymbol { get; set; }
    public int includeExpired { get; set; }
    public object comboLegs { get; set; }
    public object underComp { get; set; }
    public string comboLegsDescrip { get;set; }
    public string secIdType { get; set; }
    public string secId { get; set; }

    public Forex(string preCurrency,string baseCurrency)
    {
        //conId = 0;
        //symbol = preCurrency;
        //secType = "CASH";
        //expiry = null;
        //strike = double.Parse("0");
        //right = null;
        //multiplier = null;
        //exchange = "IDEALPRO";
        //primaryExchange = "IDEALPRO";
        //currency = baseCurrency;
        //localSymbol = null;
        //includeExpired = 0;
       // comboLegs = null;
        //underComp = null;
        //comboLegsDescrip = null;
        //secType = null;
        //secId = null;


      }
   }
 }

您可以看到我没有为类的属性分配任何值,并且无论我分配或不分配哪种值或为空,异常总是相同的。

在下面对api的描述中,我们可以看到一些带有()的属性,如strike()是双重的,一些没有()的属性,如secType作为字符串;有人告诉我,这可能是个问题。请给我有关此 COM 转换问题的任何提示:


(来源:minus.com


(来源:minus.com


(来源:minus.com

【问题讨论】:

标签: c# com casting


【解决方案1】:

你能发布一些实际上失败的代码吗?

我认为正在发生的事情是您试图将 COM 对象强制转换为普通的 .NET 类型,但这不起作用,因为 COM 对象需要通过 Runtime Callable Wrapper 或显式映射到 .NET 类型通过手动映射。

我的一个建议是跳过显式转换并使用 .NET 4.0 中的动态类型来访问您的 COM 对象的属性,然后将其映射到您需要的任何属性/对象。这样您就可以准确地看到对象的哪个部分不想映射。

【讨论】:

  • 根据您的要求,我添加了有关代码出错的图片。你能给我更多关于将 COM 对象映射到 .NET 类型或包装器的链接或解释吗?非常感谢,至少给我一些提示或正确的谷歌方向。
  • 请您查看我的另一篇文章:stackoverflow.com/questions/8477107/…
猜你喜欢
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
  • 2016-08-12
  • 2013-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多