当运行的代码此位的WriteLine显示,Equation(10, 20)
是输出到控制台:支持转换为Boolean但仍然已经使用的ToString
public class Equation
{
public int a;
public int b;
public override string ToString()
{ return "Equation(" + a + ", " + b + ")"; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new Equation() { a = 10, b = 20 });
Console.ReadLine();
}
}
我想支持Equation
实例中的测试使用一个if
所以我允许隐式转换Boolean
:
public class Equation
{
public int a;
public int b;
public override string ToString()
{ return "Equation(" + a + ", " + b + ")"; }
public static implicit operator Boolean(Equation eq)
{ return eq.a == eq.b; }
}
class Program
{
static void Main(string[] args)
{
if (new Equation() { a = 10, b = 10 })
Console.WriteLine("equal");
Console.WriteLine(new Equation() { a = 10, b = 20 });
Console.ReadLine();
}
}
但是,麻烦的是,现在,当我上Equation
使用WriteLine
,它得到的转换ŧ o Boolean
而不是使用ToString
打印。
我该如何允许隐式转换为Boolean
,仍然有WriteLine
显示使用ToString
?
更新
这个问题是由Equation
类SymbolicC++启发。下面的代码说明了一个Equation
可以经由cout
被显示以及在if
的测试中使用:
auto eq = x == y;
cout << eq << endl;
if (eq)
cout << "equal" << endl;
else
cout << "not equal" << endl;
所以这是可能以某种方式在C++中。
哇,你钉牢了Mike。谢谢! – dharmatech
虽然“方程式”在您列出的语句中工作,但似乎它们不适用于运算符'||'和'&&'。只是想我会提到这个人谁正在考虑这个选项。 – dharmatech
@dharmatech正如我所说,它不再可以转换为'布尔'。你也可以重载'&'和'|'运算符,但是它的使用是有限的,因为你仍然不能像'eq && true'这样做。我真的同意Jon的评论,认为这样的事情有点太聪明,可能会让代码和未来维护者的消费者感到困惑。 –