[英]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# 中的测试方法:
[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.";
}
将来,请提出两个不同的问题。
请不要说“它不起作用”。 这是否意味着编译错误? 运行时错误? 天网是在你的电脑上自发进化的? 请不要让我们猜测。
那说...
is
和as
不关注用户定义的转换。 您必须对Square
进行直接转换,以使其甚至考虑用户定义的转换。 (来源: Eric Lippert 的博客。我目前找不到 MSDN 参考资料。)String^
,大写“S”和克拉。 如果您需要与使用其他内容的 C/C++ 代码进行互操作,请继续使用 .Net 字符串,直到您需要调用 C/C++,然后在那里进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.