【问题标题】:Implicit type casting in C#C# 中的隐式类型转换
【发布时间】: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

标签: c# .net


【解决方案1】:

Console.WriteLine 的重载需要 boolobject(等等)。编译器更喜欢bool 因为你有一个隐式转换运算符。您可以添加 (object).ToString(),但老实说,我可能会失去运营商 - 不确定它是否对您有任何帮助。

【讨论】:

    【解决方案2】:

    嗯,这是因为您添加了一个隐式运算符。隐式关键字提供转换功能。隐式转换涉及从一种类型转换为另一种类型。 使用implicit 关键字,您可以将转换功能实现为运算符重载的运算符方法。

    链接:See this MS Doc for further explanations

    【讨论】:

    • 隐含的意思?
    • (如果是explicit,这里就好了;我想你的意思是implicit
    猜你喜欢
    • 2011-12-25
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多