【发布时间】:2020-11-29 08:28:50
【问题描述】:
在理解 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 类的布尔字段显示为输出,而不是类字段的值。
为什么会这样?
【问题讨论】:
-
旁注:公共字段几乎总是一个错误。老实说,这看起来应该是带有 get-only 属性的
readonly struct。