【发布时间】:2019-03-14 22:27:28
【问题描述】:
我正在阅读article,关于版本控制更改时可选参数如何中断。
在这里解释一下。
让我们看一下这两个概念在工作中的快速示例。认为 我们有一个类,其中一个方法具有以下签名。
// v1
public static void Redirect(string url, string protocol = "http");
这个假设的库包含一个方法,它接受两个 参数,一个必需的字符串 url 和一个可选的字符串协议。
以下显示了调用此方法的六种可能方式。
HttpHelpers.Redirect("https://haacked.com/");
HttpHelpers.Redirect(url: "https://haacked.com/");
HttpHelpers.Redirect("https://haacked.com/", "https");
HttpHelpers.Redirect("https://haacked.com/", protocol: "https");
HttpHelpers.Redirect(url: "https://haacked.com/", protocol: https");
HttpHelpers.Redirect(protocol: "https", url: https://haacked.com/");
注意参数是否可选,你可以选择 是否按名称引用参数。在最后一种情况下,请注意 参数是乱序指定的。在这种情况下,使用命名 参数是必需的。
下一个版本
使用可选参数的一个明显好处是您可以 减少 API 的重载次数。然而,依靠 可选参数确实有你需要注意的怪癖 它涉及版本控制。
假设我们已经准备好制作我们 Awesome 的第二版 HttpHelpers 库,我们添加一个可选参数到现有的 方法。
// v2
public static void Redirect(string url, string protocol = "http", bool permanent = false);
当我们尝试执行客户端而不重新编译 客户端应用程序?
我们收到以下异常消息。
Unhandled Exception: System.MissingMethodException: Method not found: 'Void HttpLib.HttpHelpers.Redirect(System.String,
System.String)'....
我很困惑为什么此更改会破坏已部署而不是重新编译的更改。
更改包含可选参数的方法签名后,它应该仍然可以工作,不是吗?即使我们不重新编译客户端应用程序,因为这是一个可选参数。
【问题讨论】:
标签: c# versioning optional-parameters