我正在使用 IL 抛出一个 Int32 并捕获它。这只是出于好奇,我并没有试图实现任何目标,所以请不要告诉我抛出异常而不是 int。
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 40 (0x28)
.maxstack 2
.locals init (object V_0,
int32 V_1)
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: ldsfld int32 ConsoleApplication3.Program::i
IL_0007: throw
} // end .try
catch [mscorlib]System.Object
{
IL_0008: stloc.0
IL_0009: nop
IL_000a: ldstr "In Object catch"
IL_000f: call void [mscorlib]System.Console::WriteLine(string)
IL_0014: nop
IL_0015: ldloc.0
IL_0016: unbox.any [mscorlib]System.Int32
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: call void [mscorlib]System.Console::WriteLine(int32)
IL_0022: nop
IL_0023: nop
IL_0024: leave.s IL_0026
} // end handler
IL_0026: nop
IL_0027: ret
} // end of method Program::Main
这不起作用,我得到字符串“In Object catch”,但是当我尝试拆箱时,我得到一个 System.InvalidCastException:指定的强制转换无效。
我怎样才能得到抛出的东西的价值?
In version 2.0 of the CLR, when a
non–CLS-compliant exception is thrown,
the CLR automatically constructs an
instance of the
RuntimeWrappedException class and
initializes its private field to refer
to the object that was actually
thrown. In effect, the CLR now turns
all non–CLS-compliant exceptions into
CLS-compliant exceptions.
try
{
// ...
}
catch (RuntimeWrappedException e)
{
int a = (int)e.WrappedException;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)