在理解C#中的类型转换时出现了一些问题。我创建了一个简单的类,并重载了其中的ToString()
方法,以便将类对象字段的值输出为字符串:
public class Triple{
public int Int32;
public string String;
public bool Boolean;
public Triple(int Int32, string String, bool Boolean)
{
this.Int32 = Int32;
this.String = String;
this.Boolean = Boolean;
}
public override string ToString()
{
return String.Format("{0},{1},{2}", this.Int32, this.String, this.Boolean);
}
我也设置了将 Triple 类的对象隐式转换为 bool 类型:
public static implicit operator bool(Triple T1)
{
if (T1.Boolean)
{
return true;
}
else
{
return false;
}
}
现在当我调用:
Triple t1 = new Triple(1, "abcd", true);
Console.WriteLine(t1);
Triple类的布尔字段显示为输出,而不是类字段的值。
为什么会这样?