【问题标题】:C# own Boolean class to pass bool by refrenceC#自己的布尔类通过引用传递bool
【发布时间】:2016-07-20 21:06:53
【问题描述】:

是否有可能以某种方式使用这个类(test.Value 不是我想要的):

RefBool test = false;
if (test)
{

}

这是类主体:

public class RefBool
{
    public bool Value { get; set; }
    public RefBool(bool value)
    {
        this.Value = value;
    }

    public static implicit operator RefBool(bool val)
    {
        return new RefBool(val);
    }

}

【问题讨论】:

  • 您可以在方法签名private void WantBoolRef(ref bool someBool) 中使用ref 关键字通过引用传递布尔值
  • 你(也)不想要public static implicit operator bool(RefBool val) { return val.Value; }吗?
  • @Iluvatar no,ref bool 是通过引用传递的值类型;它不是按值传递的。
  • 在我看来,MutableBool 是这个问题中class 的更好名称。您可以将其注入构造函数并将其保存在字段中,然后您可以随时检查该值是否已发生突变(翻转为相反的值)。像 ref bool 这样的事情你不能用同样的方式做。

标签: c# boolean ref


【解决方案1】:

是的,如果您重载 truefalse 运算符:

// note: you might want to think about what `null` means in terms of true/false
public static bool operator true(RefBool val) => val.Value;
public static bool operator false(RefBool val) => !val.Value;

不过,我不确定这是个好主意; ref bool 似乎更明显。

【讨论】:

  • 在这种情况下,C# 要求您重载operator false,这非常愚蠢。您实际使用的唯一运算符是operator true。除非我们也重载operator &,否则operator false 重载是不可能调用的。但是,重载 operator ! 可能是一个想法。
  • @JeppeStigNielsen 这是因为这些重载实际上用于驱动 ||&& 的短路行为,同时重载 |& 运算符。见this answer
  • @Kyle 我知道&& 用于调用用户定义的operator & 时可以使用operator false,但正如我所说,我们这里没有operator &。所以在这种情况下省略operator false 应该是合法的。我们的operator true 除了短路还有其他用途。
猜你喜欢
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 2012-06-06
  • 2017-08-19
相关资源
最近更新 更多