如何修复错误 CS1738 命名参数规范必须在指定所有固定参数后出现

Tâm*_*yễn 4 c#

public static Mutex CreateMutex(){
    MutexAccessRule rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
    MutexSecurity mutexSecurity = new MutexSecurity();
    mutexSecurity.AddAccessRule(rule);
    bool createdNew;
    return new Mutex(initiallyOwned: false,"Global\\E475CED9-78C4-44FC-A2A2-45E515A2436", out createdNew,mutexSecurity);
}
Run Code Online (Sandbox Code Playgroud)

错误 CS1738 命名参数规范必须在指定所有固定参数后出现

Mar*_*sch 6

所以引用 C# Doc

命名参数,当与位置参数一起使用时,只要有效

  • 因为它们后面没有任何位置参数

所以这就是原因,为什么你会遇到编译错误。

使用 C# 7.2 及更高版本时,它说:

命名参数,当与位置参数一起使用时,只要有效

  • 因为它们用于正确的位置。

有关更多信息,请参阅: 命名和可选参数


因此,如果我们看一下构造函数

public Mutex (bool initiallyOwned,
              string name,
              out bool createdNew,
              System.Security.AccessControl.MutexSecurity mutexSecurity);
Run Code Online (Sandbox Code Playgroud)

我们将看到在您的情况下,位置的顺序是正确的。如果您要切换到 C# 7.2 或更高版本,您的代码将被编译。

但是对于较低版本,您有两个选择:

  1. 删除参数命名为 initiallyOwned
  2. 对所有参数使用命名参数

喜欢:

return new Mutex(initiallyOwned: false,
                 name: "Global\E475CED9-78C4-44FC-A2A2-45E515A2436",
                 createdNew: out createdNew,
                 mutexSecurity: mutexSecurity); 
Run Code Online (Sandbox Code Playgroud)

使用第二个选项时,命名参数的位置不再重要。