当我运行这段代码时,Equation(10, 20)输出到控制台:
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();
}
}
但是,问题是,现在当我WriteLine在 an 上使用时Equation,它会转换为 aBoolean而不是使用打印ToString。
如何允许隐式转换Boolean并仍然使用WriteLine显示ToString?
更新
这个问题的灵感来自SymbolicC++Equation中的类。下面的代码说明了 an可以通过显示以及在 an 的测试中使用:Equationcoutif
auto eq = x == y;
cout << eq << endl;
if (eq)
cout << "equal" << endl;
else
cout << "not equal" << endl;
所以这在 C++ 中是可能的。