【发布时间】: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这样的事情你不能用同样的方式做。