当我运行这段代码时,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上使用Equation时,它会转换为Boolean而不是使用ToString进行打印。

如何允许隐式转换为Boolean并仍然使用WriteLine显示ToString

更新

这个问题是受SymbolicC++中的Equation类启发的。下面的代码说明了Equation可以通过cout显示,也可以在if的测试中使用:
auto eq = x == y;

cout << eq << endl;

if (eq)
    cout << "equal" << endl;
else
    cout << "not equal" << endl;

因此,这在C++中是有可能的。

最佳答案

您无法通过bool转换来做到这一点,但可以为true重载falseEquation运算符。当然Equation将不再可以隐式转换为bool,但是您仍然可以在ifwhiledofor语句和条件表达式(即?:运算符)中使用它。

public class Equation
{
    public int a;
    public int b;

    public override string ToString()
    { return "Equation(" + a + ", " + b + ")"; }

    public static bool operator true(Equation eq)
    {
        return eq.a == eq.b;
    }

    public static bool operator false(Equation eq)
    {
        return eq.a != eq.b;
    }
}

从您的示例:
if (new Equation() { a = 10, b = 10 })
    Console.WriteLine("equal"); // prints "equal"

Console.WriteLine(new Equation() { a = 10, b = 20 }); // prints Equation(10, 20)

10-08 03:00