C# 自己的布尔类通过引用传递 bool

Ilu*_*tar 3 c# boolean ref

是否可以以某种方式使用此类(test.Value 不是我正在寻找的):

RefBool test = false;
if (test)
{

}
Run Code Online (Sandbox Code Playgroud)

这是类主体:

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

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

// 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;
Run Code Online (Sandbox Code Playgroud)

不过,我不确定这是个好主意;ref bool看起来更明显了。