在理解 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 类的 bool 字段显示为输出,而不是类字段的值。为什么会这样?
最佳答案
有 Console.WriteLine
的重载采取bool
和 object
(除其他外)。编译器更喜欢 bool
因为您有一个隐式转换运算符。您可以添加 (object)
或 .ToString()
,但老实说,我可能会失去接线员 - 不确定它是否对您有所帮助。
关于c# - C#中的隐式类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65058279/