为什么在 C# 中使用 out 关键字而不是赋值?

发布于 2024-11-04 10:35:58 字数 584 浏览 3 评论 0原文

在阅读了《C# 深度》中有关它的部分后,我一直在研究 C# 中的 out 关键字。我似乎找不到一个示例来说明为什么需要关键字而不是仅分配 return 语句的值。例如:

public void Function1(int input, out int output)
{
    output = input * 5;
}

public int Function2(int input)
{
    return input * 5;
}

...
int i;
int j;

Function1(5, out i);
j = Function2(5);

i 和 j 现在具有相同的值。这只是为了能够在没有 = 符号的情况下进行初始化的便利,还是有一些我没有看到的其他派生值?我看到一些类似的答案提到它将初始化的责任转移给被调用者 这里。但是,所有这些额外的功能不仅仅是分配一个返回值并且没有 void 方法签名?

I've been investigating the out keyword in C# after reading the section about it in C# in Depth. I cannot seem to find an example that shows why the keyword is required over just assigning the value of a return statement. For example:

public void Function1(int input, out int output)
{
    output = input * 5;
}

public int Function2(int input)
{
    return input * 5;
}

...
int i;
int j;

Function1(5, out i);
j = Function2(5);

Both i and j now have the same value. Is it just the convenience of being able to initialize without the = sign or is there some other value derived that I'm not seeing? I've seen some similar answers mentioning that it shifts responsibility for initialization to the callee here. But all that extra instead of just assigning a return value and not having a void method signature?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

待"谢繁草 2024-11-11 10:35:58

通常 out 用于返回其他内容的方法,但您仍然需要从该方法获取不同的值。

一个很好的例子是 Int32.TryParse(input, out myVar) ,如果成功则返回 true,否则返回 false。您可以通过 out 参数获取转换后的 int。

int myOutVar;

if (Int32.TryParse("2", out myOutVar))
{
   //do something with the int
}else{
    //Parsing failed, show a message
}

Usually out is used for a method that returns something else, but you still need to get a different value from the method.

A good example is Int32.TryParse(input, out myVar) it will return true if it was successful and false otherwise. You can get the converted int via the out parameter.

int myOutVar;

if (Int32.TryParse("2", out myOutVar))
{
   //do something with the int
}else{
    //Parsing failed, show a message
}
花海 2024-11-11 10:35:58

C# 中的 out / ref 关键字仅应在需要返回多个值时使用。即使这样,您也应该首先考虑使用容器类型(例如 Tuple)来返回多个值,然后再恢复到 out / ref。每当您返回单个值时,都应该返回它。

The out / ref keywords in C# should only be used when you need to return multiple values. Even then you should first consider using a container type (such as Tuple) to return multiple values before you revert to out / ref. Whenever you're returning a single value it should just be returned.

苍景流年 2024-11-11 10:35:58

很多时候,使用 out 可以帮助您稍微提高性能。

考虑 IDictionary 上的 TryGetValue 方法(假设 myDictionary 是一个 IDictionary),而不是这样做:

string value = String.Empty;
if (myDictionary.ContainsKey("foo"))
{
  value = myDictionary["foo"];
}

两者 ContainsKey< /code> 和索引器需要在字典中查找键,但是您可以通过以下方式避免对正例进行双重查找:

string value;
if (!myDictionary.TryGetValue("foo", out value))
{
  value = String.Empty;
}

IMO,这是使用 out 的一个不错的理由 参数。

A lot of times, using out can help by giving you a slight performance gain.

Consider the TryGetValue method on IDictionary (say myDictionary is an IDictionary<string, string>) Rather than doing this:

string value = String.Empty;
if (myDictionary.ContainsKey("foo"))
{
  value = myDictionary["foo"];
}

Both ContainsKey and the indexer need to look up the key in the dictionary, but you can avoid this double-lookup on the positive case by going:

string value;
if (!myDictionary.TryGetValue("foo", out value))
{
  value = String.Empty;
}

IMO, that's a decent reason for using out parameters.

战皆罪 2024-11-11 10:35:58

不幸的是,我们无法在 C# 中执行如下操作:

a,b = func(x,y,z);

我们在 Python 或其他语言中执行的操作。有点克服了这一点。

我相信 F# 已经通过元组克服了这个问题。

PS:从函数返回多个值可能并不总是好的。大多数情况下,小型类型都很好 - http://www.martinfowler.com/bliki/DataClump。 html

Unfortunately we cannot do something like below in C#:

a,b = func(x,y,z);

something that we do in Python or other languages. out kind of overcomes that.

F# has overcome this with tuples I believe.

PS: Returning multiple values from a function might not be good always. Tiny types are good most of the times - http://www.martinfowler.com/bliki/DataClump.html

紫﹏色ふ单纯 2024-11-11 10:35:58

例如,如果 Int32.TryParse 解析正确并且使用 out 参数更改值,则返回布尔值。如果解析的值为 0 并且返回 true,则意味着您发送到解析的值为 0。如果它返回 false 则解析器失败。

For example, Int32.TryParse returns boolean if it parsed correctly and with the out parameter changes the value. If the parsed value is 0 and it returns true it means the value you sent to parse was 0. If it returns false then the parser failed.

瘫痪情歌 2024-11-11 10:35:58

其中一些是为了清晰起见。采用 TryParse() 方法,例如

Int32.TryParse("3", out myInt);

这将返回一个 bool,指示字符串是否能够解析为 int。
如果你刚刚

Int32.TryParse("3", myInt);

调用它会发生什么? myInt 被赋值了吗? TryParse 返回 int 吗?

这并不容易明显。但是,如果我有一个 out 参数,那么我就知道该值已被分配,并且返回的是其他内容。

Some of it is for clarity. Take the TryParse() methods, like

Int32.TryParse("3", out myInt);

This returns a bool that indicates whether the string was able to be parsed into an int.
If you just had

Int32.TryParse("3", myInt);

What happens when that's called? Is myInt assigned? Does TryParse return an int?

It's not readily apparent. But if I have an out parameter, then I know that the value is getting assigned, and that the return is something else.

梦里梦着梦中梦 2024-11-11 10:35:58

基本上你会做类似的事情(我的数据库读取)

if (ReadSingle<UserRecord>(cmd, out user))
    Cache.Insert(cacheId, user, null,
        DateTime.MaxValue, TimeSpan.FromMinutes(3));

或者你会做类似的事情:

user = ReadSingle<UserRecord>(cmd);
if(null != user)
   // Cache.Insert ...

它稍微简化了代码以使用布尔结果(从数据库读取记录)并通过 out 关键字。

Basically you do something like (my database read)

if (ReadSingle<UserRecord>(cmd, out user))
    Cache.Insert(cacheId, user, null,
        DateTime.MaxValue, TimeSpan.FromMinutes(3));

Or else you do something like:

user = ReadSingle<UserRecord>(cmd);
if(null != user)
   // Cache.Insert ...

It simplifies the code a little to use a boolean result (that a record was read from the database) and get the actual record into the variable via the out keyword.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文