【问题标题】:How to display Yes/No instead of True/False for bool? in c#如何为布尔显示是/否而不是真/假?在c#中
【发布时间】:2014-03-20 17:09:16
【问题描述】:

我收到错误“无法将类型 'string' 隐式转换为 'bool'。如何返回 'Yes' 或 'No' 而不是 true/false?

public bool? BuyerSampleSent
{
    get { bool result;
          Boolean.TryParse(this.repository.BuyerSampleSent.ToString(), out result);
        return result ? "Yes" : "No";
    }
    set { this.repository.BuyerSampleSent = value; }
}

【问题讨论】:

  • 如果你想显示一个字符串,你的类型应该是字符串而不是布尔值。
  • SO 有一个 code 格式器来在帖子中包含代码。
  • 我还编辑了您的问题以包含实际代码而不是它的图片。
  • 你不能有一个有 2 种类型的变量,比如 string 和 bool
  • TryParse 需要一个 bool 参数,这就是我将 result 声明为 bool 的原因。

标签: c# entity-framework visual-studio-2012


【解决方案1】:

如果返回类型为bool(或在本例中为bool?),则您不能返回字符串。你返回一个bool

return result;

但请注意,您要问...

如何显示是/否...

这段代码没有显示任何东西。这是对象的属性,而不是 UI 组件。在 UI 中,您可以使用此属性作为标志显示您喜欢的任何内容:

someObject.BuyerSampleSent ? "Yes" : "No"

相反,如果您希望在对象本身上显示友好的消息(也许它是一个视图模型?),那么您可以为该消息添加一个属性:

public string BuyerSampleSentMessage
{
    get { return this.BuyerSampleSent ? "Yes" : "No"; }
}

【讨论】:

  • 好的,我明白你的意思了。我使用您的建议添加了一个属性: public string BuyerSampleSentMessage { get { bool result; Boolean.TryParse(this.BuyerSampleSent.ToString(), out result);返回结果? “是”:“否”; } }
【解决方案2】:

正如@Pierre-Luc 指出的那样,您的方法返回一个布尔值。您需要将其更改为字符串。

【讨论】:

    【解决方案3】:

    您不能返回布尔值“是”或“否”。在 C# 中,bool 是布尔数据类型的关键字。您不能覆盖关键字的这种行为。
    阅读有关 C# 布尔数据类型 here 的更多信息。

    在您的情况下,您可以执行以下操作:

    public string BuyerSampleSent
    {
        get
        {
            string result= "No";
            if (this.repository.BuyerSampleSent.Equals("true",StringComparisson.OrdinalIgnoreCase)) // <-- Performance here
                result = "Yes";
            return result;
        }
        set
        {
            this.repository.BuyerSampleSent = value;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 2020-07-20
      相关资源
      最近更新 更多