我想编写一个包含 bool
值和消息的类。该消息用于解释类为何包含假值。当我使用这个类时,我想将它转换为 bool,它会返回 bool 值而不是获取属性。这可能吗?
public class ReturnResult
{
public ReturnResult(bool state, string message)
{
IsSuccess = state;
ErrorMessage = message;
}
public bool IsSuccess
{
get;
private set;
}
public string ErrorMessage
{
get;
private set;
}
}
我想做以下事情
ReturnResult rr = CallSomeFunction(a,b,c);
if ((bool) rr) {
// it is good
}
else {
// it is bad
}
最佳答案
是的,您可以覆盖 true
运算符。
public class ReturnResult
{
public ReturnResult(bool state, string message)
{
IsSuccess = state;
ErrorMessage = message;
}
public bool IsSuccess
{
get;
private set;
}
public string ErrorMessage
{
get;
private set;
}
public static bool operator true(ReturnResult returnResult) =>
returnResult.IsSuccess;
public static bool operator false(ReturnResult returnResult) =>
!returnResult.IsSuccess; // Alternatively, implement as
// returnResult ? false : true,
// avoiding duplication.
}
您还必须定义匹配的 false
运算符。现在这些行将起作用:
ReturnResult rr = CallSomeFunction(a,b,c);
if (rr) // Succeeds if the operator returns true, so if rr.IsSuccess is true.
{
// If it's good.
}
else
{
// If it's bad.
}
编辑:
正如德米特里所建议的,可能值得一提的是,您还可以将隐式转换运算符覆盖为 bool
:
public static implicit operator bool(ReturnResult returnResult) =>
returnResult.IsSuccess;
虽然 true
和 false
用于 boolean 表达式 [^1],但在撰写本文时仅限于控制语句和 ?:
三元运算符,隐式转换运算符也将允许这样的赋值:
ReturnResult rr = CallSomeFunction(a,b,c);
bool b = rr;
如果这三个都被重载,您可能想知道在 if
语句中使用了哪一个 - 答案是 the implicit conversion takes precedence, as per the spec .
[^1]:还有在&&
和||
运算符求值时,如果有用户定义的&
和 |
在类型上定义的运算符。更多信息,the spec is your friend .
关于c# - 是否可以将对象类型转换为 bool 以根据状态返回某些内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58281999/