为什么在"try“中声明的变量不在"catch”或"finally“的作用域中?

为什么在

其他每个人都提出了基础知识--块中发生的事情将保留在块中。但在.NET的情况下,检查编译器认为正在发生的事情可能会有所帮助。例如,以下面的try/catch代码为例(请注意,StreamReader是在块之外正确声明的):

代码语言:javascript运行复制static void TryCatchFinally()

{

StreamReader sr = null;

try

{

sr = new StreamReader(path);

Console.WriteLine(sr.ReadToEnd());

}

catch (Exception ex)

{

Console.WriteLine(ex.ToString());

}

finally

{

if (sr != null)

{

sr.Close();

}

}

}这将在MSIL中编译为类似于以下内容:

代码语言:javascript运行复制.method private hidebysig static void TryCatchFinallyDispose() cil managed

{

// Code size 53 (0x35)

.maxstack 2

.locals init ([0] class [mscorlib]System.IO.StreamReader sr,

[1] class [mscorlib]System.Exception ex)

IL_0000: ldnull

IL_0001: stloc.0

.try

{

.try

{

IL_0002: ldsfld string UsingTest.Class1::path

IL_0007: newobj instance void [mscorlib]System.IO.StreamReader::.ctor(string)

IL_000c: stloc.0

IL_000d: ldloc.0

IL_000e: callvirt instance string [mscorlib]System.IO.TextReader::ReadToEnd()

IL_0013: call void [mscorlib]System.Console::WriteLine(string)

IL_0018: leave.s IL_0028

} // end .try

catch [mscorlib]System.Exception

{

IL_001a: stloc.1

IL_001b: ldloc.1

IL_001c: callvirt instance string [mscorlib]System.Exception::ToString()

IL_0021: call void [mscorlib]System.Console::WriteLine(string)

IL_0026: leave.s IL_0028

} // end handler

IL_0028: leave.s IL_0034

} // end .try

finally

{

IL_002a: ldloc.0

IL_002b: brfalse.s IL_0033

IL_002d: ldloc.0

IL_002e: callvirt instance void [mscorlib]System.IDisposable::Dispose()

IL_0033: endfinally

} // end handler

IL_0034: ret

} // end of method Class1::TryCatchFinallyDispose我们看到了什么?MSIL尊重这些块--它们本质上是编译C#时生成的底层代码的一部分。作用域不仅在C#规范中是硬设置的,在CLR和CLS规范中也是如此。

作用域可以保护您,但您有时确实需要绕过它。随着时间的推移,你习惯了它,它开始感觉很自然。就像其他人所说的,在一个区块中发生的事情只会在那个区块中发生。你想分享些什么吗?你得走出街区。

📚 相关推荐

成都打胎大概需要多少钱
beat365手机下载

成都打胎大概需要多少钱

📅 07-07 👁️ 1707
快活林和绿之源哪个活性炭好
365下载手机版

快活林和绿之源哪个活性炭好

📅 07-04 👁️ 8631
「恺」详细解释
365不让提款

「恺」详细解释

📅 07-11 👁️ 296
电脑无故黑屏重启
365下载手机版

电脑无故黑屏重启

📅 07-09 👁️ 6805
苹果 iphone 5s
365不让提款

苹果 iphone 5s

📅 07-05 👁️ 6422
雀斑分离技术大概要多少钱啊?我想咨询咨询
365不让提款

雀斑分离技术大概要多少钱啊?我想咨询咨询

📅 07-03 👁️ 2701
中国青年女性在美接连失踪引关注
beat365手机下载

中国青年女性在美接连失踪引关注

📅 07-08 👁️ 8488
穿越火线怎么更新版本
365下载手机版

穿越火线怎么更新版本

📅 07-08 👁️ 9223
电信查话费的号码是多少?3种方法教你快速查询
365下载手机版

电信查话费的号码是多少?3种方法教你快速查询

📅 07-12 👁️ 2090