C#中的隐式类型转换

c#

在理解 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 类的布尔字段显示为输出,而不是类字段的值。

为什么会这样?

回答

有大量的Console.WriteLine采取boolobject(除其他外)。编译器更喜欢,bool 因为您有一个隐式转换运算符。您可以添加一个(object)or .ToString(),但老实说,我可能会失去操作员 - 不确定它在这里是否对您有帮助。


以上是C#中的隐式类型转换的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>