【问题标题】:Conversion operator in C++/Cli and use it in c#( using the as operator) and use string from c++ in c#C++/Cli 中的转换运算符并在 c# 中使用它(使用 as 运算符)并在 c# 中使用 c++ 中的字符串
【发布时间】:2015-10-23 09:13:45
【问题描述】:

如何在 c++\cli 中实现转换运算符,以便在 C# 中使用“as”运算符。

这是我在 C# 中的测试方法:

[TestMethod]
public void Test()
{
    var s = new Square(2);
    var c = new Cube(2);
    Assert.AreEqual(s.CountPerimeter(), (c as Square).CountPerimeter());
}

我尝试使用:

explicit static operator Square(Cube^ cube)
{
    Square ne(cube->GetSize());
    return ne;
}

但它不起作用。

我的方法实现。

Square::Square() {}

Square::Square(double a)
{
    _size = a;
}

Square::Square(const Square% val) // copy constructor
{
    _size = 4;
}

Square::~Square() {}

double Square::CountPerimeter()
{
    return 4 * _size;
}


Cube::Cube() {}

Cube::Cube(double a)
{
    _size = a;
}

Cube::Cube(const Cube% val)
{
    _size = 4;
}

Cube::~Cube() {}

double Cube::CountPerimeter()
{
    return 12 * _size;
}

2) 我还有第二个问题。我想在 c# 中使用 c++ 中的字符串

[Test method]
public void Test2()
{
    Assert.AreEqual("I'm a square.", s.Introduce());\
}

c++实现

#include <iostream>

string Square::Introduce()
{
    return "I'm a square.";
}

【问题讨论】:

  • 请提出两个不同的问题。如果您同时提出两个问题,很难提供一个“最佳”答案。
  • 不要返回 std::string,只有 C++ 编译器知道这意味着什么。而是返回 System::String^。并发布复制代码,SO 用户可以复制/粘贴以诊断您的问题。并且从不记录“它不起作用”。

标签: c# string c++-cli type-conversion


【解决方案1】:

以后,请提出两个不同的问题。

请不要说“它不起作用”。这是否意味着编译错误?运行时错误?天网在你的电脑上自发进化?请不要让我们猜测。

也就是说……

  1. isas 不关注用户定义的转换。您必须直接转换为 Square 以使其甚至考虑用户定义的转换。 (来源:Eric Lippert's blog。目前我找不到 MSDN 参考资料。)
  2. 始终使用 .Net 字符串。那是String^,大写字母“S”和克拉。如果您需要与使用其他内容的 C/C++ 代码进行互操作,请使用 .Net 字符串,直到您需要调用 C/C++,然后再进行转换。

【讨论】:

    猜你喜欢
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2017-07-28
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多