带 out 参数的变量范围 [英] Scope of variable with out parameter

查看:42
本文介绍了带 out 参数的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

我有以下代码块:

if (!int.TryParse("123", out var parsedNumber))
{
    return;
}

Console.WriteLine(parsedNumber);

控制台输出:123

问题:

Console.WriteLine(parsedNumber); 怎么可能知道 parsedNumber?

How is it possible, that the line Console.WriteLine(parsedNumber); knows about parsedNumber?

根据我的理解,parsedNumber 应该只在 if-block 中可用,不是吗?

According to my understanding, parsedNumber should only available in the if-block, shouldn't it?

如果我试试这个:

foreach (var data in dataList)
{
   data += "something";
}

Console.WriteLine(data);

Console.WriteLine(data); 找不到data.

我认为,解决方案是 out 参数,但我不确定.有人能解释一下吗?

I think, that the solution is the out parameter, but I'm not sure. Can someone explain this?

推荐答案

是的,因为您怀疑区别在于out"修饰符.

Yes, as you suspect the difference is that "out" modifier.

这是 C# 7 中添加的一项功能,允许您在要将变量用作参数的位置声明变量.

It is a feature added in C# 7 that allows you to declare the variable at the point where you want to use it as an argument.

这可能很方便,否则您必须在方法调用之前声明 parsedNumber.

That might be convenient as otherwise you'd have to declare parsedNumber before the method call.

您可以在此处的输出变量"下阅读更多相关信息.

You can read more about it here, under "Out variables".

https:///blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

编辑

至于为什么变量仍然在 if 之外的范围内,这肯定会令人困惑,但这是实现这一点时的设计选择,特别是对于if"情况,正是为了它可以在尝试"方法.

As for why the variable is still in scope outside of the if, that can certainly be confusing, but it was a design choice when implementing this, specifically for the "if" case and precisely so that it could be used in "try" methods.

您可以参考此评论(实际上您可以查看整个讨论以了解有关如何实现此功能的不同观点).

You can refer to this comment (actually you can take a look at the whole discussion to see the different points of view there were on how to implement this).

https://github.com/dotnet/roslyn/issues/12939#issuecomment-255650834

这篇关于带 out 参数的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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