c# - 为什么 out 参数不能有默认值?

标签 c# default-value out

目前,当尝试在一个带有 out 参数的方法中做一些事情时,我需要在方法体中分配 out 参数的值,例如

public static void TryDoSomething(int value, out bool itWorkerd)
{
    itWorkerd = true;

    if (someFavourableCondition)
    {
        // if I didn't assign itWorked variable before this point, 
        // I get an error: "Parameter itWorked must be assigned upon exit.
        return;
    }

    // try to do thing

    itWorkerd = // success of attempt to do thing
}

我希望能够设置 itWorked 参数的默认值,这样我就不必在方法主体中任意设置值。

public static void TryDoSomething(int value, out bool itWorkerd = true)
{
    if (someFavourableCondition)
    {
        // itWorked was already assigned with a default value
        // so no compile errors.
        return;
    }

    // try to do thing

    itWorkerd = // success of attempt to do thing
}

为什么不能为 out 参数分配默认值?

最佳答案

默认值可用于按值传递的参数。参数仍然传递给函数,但如果代码省略参数,编译器会提供缺失值。

您提出的功能完全不同。您建议允许函数的实现者省略设置值,而不是调用者省略传递值。所以,这是一个完全不同的功能。为什么没有实现?以下是一些可能的原因:

  1. 没有人想到要实现这个功能。
  2. 设计人员考虑了该功能并拒绝了它,因为它不够有用,不值得为实现付出代价。
  3. 设计人员考虑了该功能并拒绝了它,因为它令人困惑,因为它使用与默认值参数相似的语法,但具有完全不同的含义。

关于c# - 为什么 out 参数不能有默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23933450/

相关文章:

javascript - 未捕获的类型错误 : NaN JavaScript Sharepoint

Java 索引越界异常

用于添加默认参数的 C++ 特定语法

mysql - 从带有日期时间的选择创建临时表会导致无效的默认值错误

java - 什么是 “2”命令,同时将System.out和System.err Java消息都重定向到文件时

authentication - Google Auth2.0 登出

c# - 将 CollectionBase 转换为 List 或可与 Linq 一起使用的数据类型

c# - 如何在 ASP.NET MVC 5 的两个不同 Controller 中访问具有相同名称的操作方法?

c# - Redis 缓存实现 - c#

ruby-on-rails - 列的默认值