【问题标题】:Is it possible to type casting an object to bool to return something depends on the state?是否可以将对象类型转换为 bool 以返回取决于状态的内容?
【发布时间】:2020-02-05 11:36:43
【问题描述】:

我想编写一个包含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
}

【问题讨论】:

  • 为什么不做 if(rr.IsSuccess) ?
  • 我强烈建议使用@auburg 提供的解决方案。它直截了当,易于阅读,并不意味着必须根据状态了解不同类型的 ReturnResult
  • 只是出于好奇:这是否意味着您也想将其转换为 (string) 以获取 ErrorMessage
  • 嗨 Monh Zhu,不,因为我认为这很混乱。
  • 好吧,顺便说一句,如果您想直接称呼某人,请在姓名前使用 @,然后此人会收到通知。

标签: c# casting boolean operator-overloading


【解决方案1】:

是的,您可以覆盖 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.
}

编辑: 正如 Dmitry 所建议的,可能值得一提的是,您还可以将隐式转换运算符覆盖为 bool

public static implicit operator bool(ReturnResult returnResult) => 
    returnResult.IsSuccess;

虽然truefalse 在布尔表达式[^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

【讨论】:

  • 您还可以向 OP 提及这个正确的解决方案实际上比 if (rr.IsSuccess) 更长...
  • 不可能实现bool operator
  • @Stefan 这些是truefalse 运算符。他们都返回bool。请参阅规范以供参考:docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
  • 感谢您添加参考
  • public static implicit operator bool(ReturnResult value) => value != null && value.IsSuccess; 是另一种可能
【解决方案2】:

如果你这样写它应该可以工作(我不会投):

ReturnResult rr = CallSomeFunction(a,b,c);
if (rr.IsSuccesss) {
  // it is good
}
else {
  // it is bad
}

【讨论】:

  • 是的。我知道。我想知道有没有更好的方法。
猜你喜欢
  • 1970-01-01
  • 2013-01-09
  • 2011-02-24
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多