为什么out参数没有默认值? [英] Why can't an out parameter have a default value?

查看:114
本文介绍了为什么out参数没有默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,当尝试在采用out参数的方法中执行某些操作时,我需要在方法主体中分配out参数的值,例如

Currently when trying to do something in a method that takes an out parameter, I need to assign the value of the out parameter in the method body, e.g.

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
}

我希望能够设置<$ c $的默认值c> itWorked 参数,因此我不必在方法的主体中随意设置值。

I'd like to be able to set a default value of the itWorked parameter so I don't have to arbitrarily set the value in the body of the method.

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 参数的值是什么?

Why is it not possible to assign a default value for an out parameter?

推荐答案

参数的默认值可用通过价值传递。该参数仍会传递给函数,但是如果代码省略了该参数,则编译器将提供缺少的值。

Default values are available for parameters passed by value. The parameter is still passed to the function but if the code omits the parameter, the compiler supplies the missing value.

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

Your proposed feature is quite different. Instead of the caller omitting to pass the value, you propose to allow the implementer of the function to omit setting the value. So, this is a quite different feature. Why was it not implemented? Here are some possible reasons:


  1. 没人想到要实现此功能。

  2. 设计师认为

  3. 设计人员考虑了该功能,并认为它令人困惑,因为它使用与默认值参数相似的语法,但具有以下缺点:完全不同的意思。

这篇关于为什么out参数没有默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆