在谈论 C# 7.2 引用扩展方法时,“this ref”和“ref this”有什么区别?

taq*_*ion 7 c# extension-methods ref c#-7.2

考虑以下扩展方法:

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

public static void Toggle2(ref this bool @bool) => @bool = !@bool;
Run Code Online (Sandbox Code Playgroud)

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

class Foo
{
    private bool _flag;
    public void DoWork()
    {
        _flag.Toggle();
        Console.WriteLine(_flag);
        _flag.Toggle2();
        Console.WriteLine(_flag);
    }
}
Run Code Online (Sandbox Code Playgroud)

我们得到:

True
False
Run Code Online (Sandbox Code Playgroud)

问题:选择一种语法或另一种语法是否存在隐藏的差异?

Joe*_*orn 2

没有区别。这些称为修饰符,并且它们在规范中的顺序未定义

您可以在此处阅读C# 语言规范中有关方法参数的部分:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#method-parameters

它列出了不同的选项并定义了它们如何交互和混合,但没有说明您必须使用什么顺序。