当我运行这段代码时,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();
}
}
Run Code Online (Sandbox Code Playgroud)
我想支持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();
}
}
Run Code Online (Sandbox Code Playgroud)
然而,麻烦的是,现在,当我使用WriteLine上Equation,它得到的转换为Boolean而不是使用打印的ToString.
如何允许隐式转换Boolean并仍然WriteLine使用ToString?
更新
这个问题的灵感来自SymbolicC++中的Equation类.下面的代码说明了一个可以通过被显示以及在一个试验中使用:Equationcoutif
auto eq = x == y;
cout << eq << endl;
if (eq)
cout << "equal" << endl;
else
cout << "not equal" << endl;
Run Code Online (Sandbox Code Playgroud)
所以这在C++中是可行的.
Jon*_*eet 12
据我所知,你不能.您还可以提供转换为字符串...但这会使调用WriteLine(string)与WriteLine(bool` 之间的模糊不清.
我个人强烈建议你放弃隐式转换Boolean.隐式转换几乎总是一个坏主意.它们使代码更加混乱,并且导致意外的过载更改,如您所发现的那样.
(我也会改变你的支撑风格,但这是另一回事.)
这是因为调用Console.WriteLine(bool)重载而不是Console.WriteLine(对象).您可以显式转换为对象,并将调用所需的重载:
Console.WriteLine((object)(new Equation() { a = 10, b = 20 }));
Run Code Online (Sandbox Code Playgroud)
或者明确地调用.ToString():
Console.WriteLine((new Equation() { a = 10, b = 20 }).ToString());
Run Code Online (Sandbox Code Playgroud)
您无法通过bool转换执行此操作,但可以重载true和false运算符Equation.当然Equation不会是隐式转换为bool任何更多,但你仍然可以使用它在if,while,do,和for语句和条件表达式(即?:运营商).
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;
}
}
Run Code Online (Sandbox Code Playgroud)
从你的例子:
if (new Equation() { a = 10, b = 10 })
Console.WriteLine("equal"); // prints "equal"
Console.WriteLine(new Equation() { a = 10, b = 20 }); // prints Equation(10, 20)
Run Code Online (Sandbox Code Playgroud)