目前,当尝试在一个带有 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
参数分配默认值?
最佳答案
默认值可用于按值传递的参数。参数仍然传递给函数,但如果代码省略参数,编译器会提供缺失值。
您提出的功能完全不同。您建议允许函数的实现者省略设置值,而不是调用者省略传递值。所以,这是一个完全不同的功能。为什么没有实现?以下是一些可能的原因:
- 没有人想到要实现这个功能。
- 设计人员考虑了该功能并拒绝了它,因为它不够有用,不值得为实现付出代价。
- 设计人员考虑了该功能并拒绝了它,因为它令人困惑,因为它使用与默认值参数相似的语法,但具有完全不同的含义。
关于c# - 为什么 out 参数不能有默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23933450/