【发布时间】:2014-07-18 23:10:03
【问题描述】:
目前,当尝试在带有 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 参数分配默认值?
【问题讨论】:
-
可能是因为它对调用者没有任何改变。您只是将赋值语句从方法的第一行移至参数列表。常规的默认参数会在所有调用者中分配(排序),因此它会改变外部行为。您要求的是几乎没有任何价值的语法糖。
-
方法的调用者如何表明他们希望应用默认值?现在想想,在你的方法完成后,调用者如何获取
out参数的值? -
我认为这与能够忽略返回值一样有意义 - 很有意义。我想没有人认为这很重要(我认为不是),或者正如 Eric Lippert 经常说的那样,与它的附加值相比,实施起来成本太高。
-
我不同意您的断言,即您必须“任意设置值”。您签约为调用者提供
Boolean值。没有什么武断的。您对价值做出有意识的决定并提供它。如果您事先不知道该值应该是什么,那么在这种情况下您可能不应该使用out。
标签: c# default-value out