首页 > 解决方案 > 在谈论 C# 7.2 ref 扩展方法时,“this ref”和“ref this”有什么区别?

问题描述

考虑以下扩展方法:

public static void Toggle(this ref bool @bool) => @bool = !@bool;

public static void Toggle2(ref this bool @bool) => @bool = !@bool;

这些只是切换一个 ref 布尔变量值。测试:

class Foo
{
    private bool _flag;
    public void DoWork()
    {
        _flag.Toggle();
        Console.WriteLine(_flag);
        _flag.Toggle2();
        Console.WriteLine(_flag);
    }
}

我们得到:

True
False

问题:选择一种语法或另一种语法有什么隐藏的区别吗?

标签: c#extension-methodsrefc#-7.2

解决方案


不,它们完全相同,就像(现在)您可以使用$@或编写插入的逐字字符串文字@$


推荐阅读