2022/12/11

[C#] 如何修正錯誤 CS1738 "named argument specifications must appear after all fixed arguments have been specified" 問題

問題

最近遇到客戶拿到原始碼在編譯過程出現 "CS1738 named argument specifications must appear after all fixed arguments have been specified" 錯誤

中文錯誤訊息 "CS1738 必須在所在固定引數皆已指定之後,具名引數規格才可出現。請使用語言版本 7.2 或更高的版本,以允許非後置的具名引數。"

  • 開發環境: 使用 VS2022
  • 客戶環境: 使用 VS2017

相同的程式,在 VS2022 下編譯沒有問題,而在 VS2017 卻遇到無法正確編譯。

程式大致如下:

context.MapRoute(
  name: "MyRouteName",
  url: "MyArea/News/{type}",
  new { controller = "News", action = "TypeList" }
);

解決方法

  1. 依照參數位置給予對應值, 不加任何具名引數 (把具名引數 name:url: 都拿掉)
  2. 把所有具名引數都加上去, 即第三個參數前須加上具名引數 defaults:
  3. 更新 Visual Studio 到新版本 (需支援 C# 7.2 以上的版本)

相關連結