【问题标题】:Creating a KeyValuePair in Managed C++在托管 C++ 中创建 KeyValuePair
【发布时间】:2008-12-05 15:44:47
【问题描述】:

我还有另一个托管 C++ KeyValuePair 问题,我知道在 C# 中可以做什么,但是很难转换为托管 C++。这是我想在 C# 中执行的代码:

KeyValuePair<String, String> KVP = new KeyValuePair<string, string>("this", "that");

我已经将它反映到 MC++ 中并得到了这个:

KeyValuePair<String __gc*, String __gc*> __gc* KVP = (S"this", S"that");

我正在翻译的:

KeyValuePair<String ^, String ^> KVP = (gcnew String("this"), gcnew String("that"));

我从我的previous question 知道 KeyValuePair 是一个值类型;问题是它是 C++ 中的值类型和 C# 中的引用类型吗?谁能告诉我如何从 C++ 设置 KeyValuePair 的键和值?

【问题讨论】:

    标签: .net generics visual-c++ .net-2.0 managed-c++


    【解决方案1】:

    应该这样做:

    KeyValuePair&lt; String ^, String ^&gt; k(gcnew String("Foo"), gcnew String("Bar"));

    KeyValuePair 是不可变类型,所以你必须将所有内容都传递给构造函数,它看起来和 C# 中的一样,只是如果对象在堆栈上,你会这样写。

    【讨论】:

    • KeyValuPair 不是不可变类型。
    • 这也行得通,但我不能同时接受,所以我投了你们俩的票。
    • 其实是不可变的。这是设计师的帖子,解释了为什么connect.microsoft.com/VisualStudio/feedback/…
    • 由于引用不可变,切换到此作为最佳答案
    【解决方案2】:

    试试

    System::Collections::Generic::KeyValuePair< System::String^, System::String^>^ k = gcnew System::Collections::Generic::KeyValuePair< System::String^, System::String^>(gcnew System::String("foo") ,gcnew System::String("bar"))   ;
    

    【讨论】:

    • 这行得通,但我不知道为什么。 KeyValuePair 是值类型吗?
    猜你喜欢
    • 2011-02-07
    • 2013-01-05
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2011-04-21
    • 1970-01-01
    相关资源
    最近更新 更多