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

问题描述 投票:0回答:1

在 swift 中,只需在 var 上调用

Boolean
即可切换
.toggle()

var isVisible = false
isVisible.toggle()  // true

我想在 C# 中创建相同的功能,所以我在

bool

上编写了一个扩展方法
public static class Utilities {
    public static void Toggle(this bool variable) {
        variable = !variable;
        //bool temp = variable;
        //variable = !temp;
    }
} 

但是,它不起作用,我怀疑这与 C# 中的

bool
是值类型有关,而它们在 swift 中是引用类型。

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

c# boolean extension-methods
1个回答
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);
    }
}

输出:

before: True
after: False

注意: 此功能仅从 C# 7.2 起可用。请参阅此处

© www.soinside.com 2019 - 2024. All rights reserved.