[英]How to display Yes/No instead of True/False for bool? in c#
I get the error "Cannot implicitly convert type 'string' to 'bool'. How do I return 'Yes' or 'No' instead of true/false? 我收到错误消息“无法将类型'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; }
}
You can't return a string if the return type is bool
(or bool?
in this case). 如果返回类型为bool
(在这种情况下为bool?
,则不能返回字符串。 You return a bool
: 您返回bool
:
return result;
Notice, however, that you ask... 但是请注意,您要求...
How to display Yes/No... 如何显示是/否...
This code isn't displaying anything. 此代码未显示任何内容。 This is a property on an object, not a UI component. 这是对象的属性,而不是UI组件的属性。 In the UI you can display whatever you like using this property as a flag: 在用户界面中,您可以使用此属性作为标志来显示任意内容:
someObject.BuyerSampleSent ? "Yes" : "No"
Conversely, if you want a display-friendly message on the object itself (perhaps it's a view model?) then you can add a property for that message: 相反,如果您希望在对象本身上显示友好的消息(也许是视图模型?),则可以为该消息添加属性:
public string BuyerSampleSentMessage
{
get { return this.BuyerSampleSent ? "Yes" : "No"; }
}
Your method returns a bool as @Pierre-Luc points out. 如@ Pierre-Luc所指出的,您的方法将返回布尔值。 You need to change that to a String. 您需要将其更改为字符串。
You cannot return a bool value "Yes" or "No". 您不能返回布尔值“是”或“否”。 In C#, bool is a keyword for Boolean Data Type.You cannot override this behavior of a keyword. 在C#中, bool是布尔数据类型的关键字。您不能覆盖关键字的这种行为。
Read more about C# Boolean Data Type here . 在此处阅读有关C#布尔数据类型的更多信息。
In your case you can do the following: 根据您的情况,您可以执行以下操作:
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.