对于将System.Object作为类型过滤器的一般catch子句的任何实际影响?

时间:2012-12-31 09:55:54

标签: c# .net cil

我记得曾经听过,抛出System.Exception以外的某种类型的对象(或那些扩展它的对象)在技术上是合法的CIL,尽管C#没有支持它的功能。所以我有兴趣看到以下C#代码:

try {
    throw new Exception();
} catch(Exception x) {
    try {
        throw;
    } catch {
        Console.Write("yes");
    }
}

编译为以下CIL:

  .try
  {
    IL_0000:  newobj     instance void [mscorlib]System.Exception::.ctor()
    IL_0005:  throw
  }  // end .try
  catch [mscorlib]System.Exception 
  {
    IL_0006:  pop
    .try
    {
      IL_0007:  rethrow
    }  // end .try
    catch [mscorlib]System.Object 
    {
      IL_0009:  pop
      IL_000a:  ldstr      "yes"
      IL_000f:  call       void [mscorlib]System.Console::Write(string)
      IL_0014:  leave.s    IL_0016
    }  // end handler
    IL_0016:  leave.s    IL_0018
  }  // end handler

我们看到嵌套的常规catch子句编译为:

catch [mscorlib]System.Object 

在C#中,对于将System.Object作为类型过滤器而非System.Exception的一般catch子句有任何实际影响吗?

1 个答案:

答案 0 :(得分:3)

是.NET-2.0之前的差异。我在.NET 1.1天里读过它。

It is explained here (I won't copy it)。请注意,第一个答案是错误的,第二个答案是对的。

关于它是否实用:不。我想这对于模糊的互操作场景很重要。