C++/Cli 中的转换运算符并在 c# 中使用它(使用 as 运算符)并在 c# 中使用 c++ 中的字符串
Conversion operator in C++/Cli and use it in c#( using the as operator) and use string from c++ in c#
如何在 c++\cli 中使用 "as" 运算符在 C# 中使用转换运算符。
这是我在 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.";
}
以后请问两个不同的问题。
请不要说"it does not work"。这是否意味着编译错误?运行时错误?天网是在你的电脑上自发进化的?请不要让我们猜测。
也就是说...
is
和 as
不关注用户定义的转换。您必须直接转换为 Square
才能使其甚至考虑用户定义的转换。 (来源:Eric Lippert's blog。目前我找不到这方面的 MSDN 参考。)
- 始终使用 .Net 字符串。那是
String^
,大写 "S",克拉。如果您需要与使用其他东西的 C/C++ 代码进行互操作,请继续使用 .Net 字符串,直到您需要调用 C/C++,然后在那里进行转换。
如何在 c++\cli 中使用 "as" 运算符在 C# 中使用转换运算符。
这是我在 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.";
}
以后请问两个不同的问题。
请不要说"it does not work"。这是否意味着编译错误?运行时错误?天网是在你的电脑上自发进化的?请不要让我们猜测。
也就是说...
is
和as
不关注用户定义的转换。您必须直接转换为Square
才能使其甚至考虑用户定义的转换。 (来源:Eric Lippert's blog。目前我找不到这方面的 MSDN 参考。)- 始终使用 .Net 字符串。那是
String^
,大写 "S",克拉。如果您需要与使用其他东西的 C/C++ 代码进行互操作,请继续使用 .Net 字符串,直到您需要调用 C/C++,然后在那里进行转换。