【问题标题】:UWP - InvalidCastException when accessing ProductListing.CurrencyCodeUWP - 访问 ProductListing.CurrencyCode 时出现 InvalidCastException
【发布时间】:2017-04-29 17:13:22
【问题描述】:

我正面临一个非常奇怪的问题。 我需要将 ProductListing 项目的 CurrencyCode 属性存储在 WSA_10_0 环境中。

这里是代码

foreach (ProductListing product in listings.ProductListings.Values)
{
    Debug.Log("CURRENCY_CODE/"+product.CurrencyCode);
}

尝试执行代码时出现以下错误

附加信息:无法转换类型的对象 'Windows.ApplicationModel.Store.ProductListing' 键入 'Windows.ApplicationModel.Store.IProductListing2'。

现在,这真的很奇怪,因为 as this documentation page states ProductListing 对象继承自 IProductListing2

整个异常内容都在这里

System.InvalidCastException occurred
  HResult=-2147467262
  Message=Unable to cast object of type 'Windows.ApplicationModel.Store.ProductListing' to type 'Windows.ApplicationModel.Store.IProductListing2'.
  Source=mscorlib
  StackTrace:
       at System.StubHelpers.StubHelpers.GetCOMIPFromRCW_WinRT(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget)
       at Windows.ApplicationModel.Store.ProductListing.get_CurrencyCode()
       at CI.WSANative.IAPStore.WSANativeStore.<GetProductListingsAsync>d__5.MoveNext()
  InnerException: 

更新:

我尝试访问列表对象的 CurrencyCode 属性,该属性的类型为 ListingInformation,尽管它应该具有该属性 basing on the class documentation,但它给出了类似的错误。

附加信息:无法转换类型的对象 'Windows.ApplicationModel.Store.ListingInformation' 键入 'Windows.ApplicationModel.Store.IListingInformation2'。

【问题讨论】:

  • 能否提供您所在的代码casting
  • 这就是重点,我没有投任何东西。似乎正在进行一些隐式转换,好像它在对象类型中找不到 CurrencyCode 属性
  • 你能在foreach循环中删除你的.Values吗?
  • 我认为这无关紧要,因为我刚刚发现 ListingInformation 类型的列表对象也具有 CurrencyCode 属性,并且以相同的方式失败。 Additional information: Unable to cast object of type 'Windows.ApplicationModel.Store.ListingInformation' to type 'Windows.ApplicationModel.Store.IListingInformation2'. 我开始认为这可能与某种 API 不匹配有关
  • listings.ProductListings.Values的返回类型是什么?

标签: c# uwp .net-core


【解决方案1】:

CurrencyCode 属性以及 IListingInformation2 接口是在 Windows 版本 10586 上引入的。如果您针对 10586 或更新的 SDK 构建应用程序,您将能够在代码中使用它,但如果您在机器上运行应用程序在 Windows 版本 10240 中,CLR 仍会尝试调用该方法,方法是首先在您的 Windows 运行时对象上为属性 getter 所在的接口(在 CurrencyCode 情况下为 IListingInformation2)执行查询接口,但查询接口调用将失败,并且CLR 将抛出 InvalidCastException。

【讨论】:

  • 所以UWP毕竟不是那么普遍......我是否必须假设使用该属性根本不安全?最后,我做了一个解决方法,从 RegionInfo 而不是 ListingInformation 获取 CurrencyCode。您是否知道这种方法可能会失败的任何边缘情况?是否有任何其他方式可以更可靠地访问该信息?
  • 嗯......你有几个选择:1)检测故障条件并以某种方式制定后备计划; 2) 在您的 AppX 清单中指定支持的最低 Windows 版本为 10586; 3) 不要使用那个 API。
  • @SergioBonfiglio 这个解决方案对你有用吗?我也遇到了同样的问题,但是提高最低 SDK 版本并没有为我解决。
  • @Joseph 我相信是这样,已经很久了,从那以后我改变了项目和公司。恐怕我无法提供更具体的帮助。
猜你喜欢
  • 1970-01-01
  • 2018-05-21
  • 2017-10-26
  • 2020-10-13
  • 2011-08-31
  • 1970-01-01
  • 2013-05-15
  • 2017-11-01
  • 1970-01-01
相关资源
最近更新 更多