是否可以通过在 C# 中的同一变量上调用扩展方法来更改 bool 值?

Ahm*_*mad 4 c# extension-methods boolean

在 swift 中,可以Boolean通过简单地调用.toggle()var 来切换 a。

var isVisible = false
isVisible.toggle()  // true
Run Code Online (Sandbox Code Playgroud)

我想在 C# 中创建相同的功能,所以我在“bool”上编写了一个扩展方法

public static class Utilities {
    public static void Toggle(this bool variable) {
        variable = !variable;
        //bool temp = variable;
        //variable = !temp;
    }
} 
Run Code Online (Sandbox Code Playgroud)

然而,它不起作用,我怀疑它与boolC# 中的值类型有关,而它们在 swift 中是引用类型。

有没有办法在 C# 中实现相同的切换功能?

woh*_*tad 14

您可以通过引用接受对象来做到这一点:this bool

public static class Utilities
{
    //-----------------------------vvv
    public static void Toggle(this ref bool variable)
    {
        variable = !variable;
    }
}

class Program
{
    static void Main(string[] args)
    {
        bool b1 = true;
        Console.WriteLine("before: " + b1);
        b1.Toggle();
        Console.WriteLine("after: " + b1);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

before: True
after: False
Run Code Online (Sandbox Code Playgroud)

注意:此功能仅在 C# 7.2 中可用。看这里