什么时候应该使用out参数?什么时候、参数、out

2023-09-02 01:56:59 作者:怎能淡忘

我不明白什么时候应该使用输出参数,我亲自包装的结果在一个新的类型,如果我需要返回多个类型,我觉得轻松了许多工作比了。

I don't understand when an output parameter should be used, I personally wrap the result in a new type if I need to return more than one type, I find that a lot easier to work with than out.

我见过的方法,

   public void Do(int arg1, int arg2, out int result)

是否有任何情况下,这实际上是有意义的?

are there any cases where that actually makes sense?

怎么样的TryParse ,为什么不返回 ParseResult 键入?或在较新的框架返回一个为空的类型?

how about TryParse, why not return a ParseResult type? or in the newer framework return a null-able type?

推荐答案

当你有一个 TryNNN 函数输出还是不错的,很明显,该输出参数将永远是设置,即使该函数不会成功。这可以让你依靠的事实,你声明的局部变量将被设置,而不是后来把支票兑零的code。 (下面留言表示该参数可以设置为,所以你可能要以验证你打电话,以确保该函数的文档,如果是这样的话还是不行。)它使codea的更清晰,更易于阅读。另一种情况是,当你需要返回的方法的条件下一些数据和状态,如:

Out is good when you have a TryNNN function and it's clear that the out-parameter will always be set even if the function does not succeed. This allows you rely on the fact that the local variable you declare will be set rather than having to place checks later in your code against null. (A comment below indicates that the parameter could be set to null, so you may want to verify the documentation for the function you're calling to be sure if this is the case or not.) It makes the code a little clearer and easier to read. Another case is when you need to return some data and a status on the condition of the method like:

public bool DoSomething(int arg1, out string result);

在这种情况下,返回可以指示如果函数成功且结果被存储在输出参数。诚然,这个例子是人为的,因为你可以设计一种方法,其中的函数只返回一个字符串,但你的想法。

In this case the return can indicate if the function succeeded and the result is stored in the out parameter. Admittedly, this example is contrived because you can design a way where the function simply returns a string, but you get the idea.

一个缺点是,你必须要声明一个局部变量使用它们:

A disadvantage is that you have to declare a local variable to use them:

string result;
if (DoSomething(5, out result))
    UpdateWithResult(result);

相反的:

UpdateWithResult(DoSomething(5));

不过,这甚至有可能不会吃亏,这取决于你要去的设计。在日期时间的情况下,两个装置(解析和的TryParse)被提供

However, that may not even be a disadvantage, it depends on the design you're going for. In the case of DateTime, both means (Parse and TryParse) are provided.