[英]How to display Yes/No instead of True/False for bool? in c#
我收到错误消息“无法将类型'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; }
}
如果返回类型为bool
(在这种情况下为bool?
,则不能返回字符串。 您返回bool
:
return result;
但是请注意,您要求...
如何显示是/否...
此代码未显示任何内容。 这是对象的属性,而不是UI组件的属性。 在用户界面中,您可以使用此属性作为标志来显示任意内容:
someObject.BuyerSampleSent ? "Yes" : "No"
相反,如果您希望在对象本身上显示友好的消息(也许是视图模型?),则可以为该消息添加属性:
public string BuyerSampleSentMessage
{
get { return this.BuyerSampleSent ? "Yes" : "No"; }
}
如@ Pierre-Luc所指出的,您的方法将返回布尔值。 您需要将其更改为字符串。
您不能返回布尔值“是”或“否”。 在C#中, bool是布尔数据类型的关键字。您不能覆盖关键字的这种行为。
在此处阅读有关C#布尔数据类型的更多信息。
根据您的情况,您可以执行以下操作:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.