【问题标题】:^Uri to GetAsync^Uri to GetAsync
【发布时间】:2017-07-25 11:02:49
【问题描述】:

我也是 UWP 和 c++ 的新手。 我正在尝试编写一个处理 http-api 的简单应用程序。 我的例子:

void ForecastFromMSW::MainPage::GetTheCity(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    String ^mystr = "http://google.com"; // creating a string object 
    Uri url(mystr); // crating an url object
    HttpClient cli; //creating an object of HttpClient
    cli.GetAsync(url); // pass url object to cli
}

来自编译器的消息:

1>------ Build started: Project: ForecastFromMSW, Configuration: Debug Win32 ------
1>  MainPage.xaml.cpp
1>c:\users\9maf4you\documents\visual studio 2015\projects\forecastfrommsw\forecastfrommsw\mainpage.xaml.cpp(38): error C2664: 'Windows::Foundation::IAsyncOperationWithProgress<Windows::Web::Http::HttpResponseMessage ^,Windows::Web::Http::HttpProgress> ^Windows::Web::Http::HttpClient::GetAsync(Windows::Foundation::Uri ^,Windows::Web::Http::HttpCompletionOption)': cannot convert argument 1 from 'Windows::Foundation::Uri' to 'Windows::Foundation::Uri ^'
1>  c:\users\9maf4you\documents\visual studio 2015\projects\forecastfrommsw\forecastfrommsw\mainpage.xaml.cpp(38): note: No user-defined-conversion operator available, or
1>  c:\users\9maf4you\documents\visual studio 2015\projects\forecastfrommsw\forecastfrommsw\mainpage.xaml.cpp(38): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========

我明白了,编译器无法将一种类型转换为另一种类型,我知道我必须将 ^Uri 传递给 GetAsync。但我不知道我应该怎么做。 谢谢。

【问题讨论】:

    标签: uwp c++-cx


    【解决方案1】:

    在 C++/CX 中,对象通常使用ref new 实例化,返回一个引用计数的对象句柄。修复代码的最简单方法是替换

    Uri url(mystr);
    

    Uri^ url = ref new Uri(mystr);
    

    当超出范围时,编译器将生成代码以减少url 上的引用计数。当引用计数为零时,对象会自动销毁。

    【讨论】:

      【解决方案2】:

      编译器告诉你问题

      无法将参数 1 从 'Windows::Foundation::Uri' 转换为 'Windows::Foundation::Uri ^'

      解决方法是使用托管的“地址”运算符,即%cli.GetAsync(%url);。您可以通过一个非常简单的测试程序看到同样的问题:

      ref class Foo sealed {};
      void f(Foo^) {}
      
      int main(array<System::String ^> ^args)
      {
          Foo foo;
          f(%foo);
          return 0;
      }
      

      请注意,由于您调用的是 *Async() 方法,因此您可能需要认真考虑使用 C#。

      【讨论】:

      • 问题是关于 C++/CX,而不是 C++/CLI。您的回答不适用。
      猜你喜欢
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2016-04-20
      • 2013-11-03
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      相关资源
      最近更新 更多