2016-10-07 48 views
22

为了说明我的问题,考虑这些简单的例子(C#):为什么'unbox.any'不能像'castclass'那样提供有用的异常文本?

object reference = new StringBuilder(); 
object box = 42; 
object unset = null; 

// CASE ONE: bad reference conversions (CIL instrcution 0x74 'castclass') 
try 
{ 
    string s = (string)reference; 
} 
catch (InvalidCastException ice) 
{ 
    Console.WriteLine(ice.Message); // Unable to cast object of type 'System.Text.StringBuilder' to type 'System.String'. 
} 
try 
{ 
    string s = (string)box; 
} 
catch (InvalidCastException ice) 
{ 
    Console.WriteLine(ice.Message); // Unable to cast object of type 'System.Int32' to type 'System.String'. 
} 

// CASE TWO: bad unboxing conversions (CIL instrcution 0xA5 'unbox.any') 
try 
{ 
    long l = (long)reference; 
} 
catch (InvalidCastException ice) 
{ 
    Console.WriteLine(ice.Message); // Specified cast is not valid. 
} 
try 
{ 
    long l = (long)box; 
} 
catch (InvalidCastException ice) 
{ 
    Console.WriteLine(ice.Message); // Specified cast is not valid. 
} 
try 
{ 
    long l = (long)unset; 
} 
catch (NullReferenceException nre) 
{ 
    Console.WriteLine(nre.Message); // Object reference not set to an instance of an object. 
} 
在我们试图引用转换(对应于CIL指令 castclass)的情况下

所以,抛出的异常包含表单的一个极好的消息, :

无法投射'X'类型的对象以键入'Y'。

经验证据显示,这条短信通常对需要处理问题的(有经验或缺乏经验的)开发人员(缺陷修复人员)非常有帮助。

相比之下,当尝试拆箱(unbox.any)失败时,我们收到的消息是无法提供信息的。有什么技术上的原因,为什么这一定是如此?

指定的转换无效。 [无用]

换句话说,我们为什么不接收等(我的话)的消息:

无法拆箱类型的“X”的对象成Y型的”的值“; 这两种类型必须同意。

分别(再次我的话):

无法拆箱空引用到非空类型“Y”的值。

因此,重复我的问题:在一个案例中的错误信息是好的和信息丰富的,而在另一个案例中是差的是“偶然的”?或者是否有一个技术原因,为什么运行时不可能提供或者非常难以提供第二种情况下遇到的实际类型的细节?

(我见过一对夫妇的线程在这里让我相信绝不会有人问,如果失败unboxings的异常文本一直比较好。)


更新:丹尼尔弗雷德里科·林斯莱特的回答导致他在CLR Github上开启一个问题(见下文)。这被发现是早期问题的复制品(由Jon Skeet提出,人们几乎猜到了!)。所以没有很好的理由来解释这个糟糕的异常消息,而且人们已经将它固定在CLR中。所以我不是第一个想知道这个的。我们可以期待这一改进在.NET Framework中出现的那一天。

+1

乔恩[已经问过这个问题(http://stackoverflow.com/questions/1583050/performance-surprise-with-as-and-nullable-types)。大致。同样的原因,这必须在.NET 1.x时间内生成紧凑且快速的代码。如果你想要一个很好的异常消息,那么你必须编写代码'Convert.ToInt64(reference)'。仍然非常紧凑,不如一样快。 –

+1

@HansPassant所以你链接的问题是关于为什么模式'var nullable = box作为int?如果(nullable.HasValue){/ *使用nullable.Value * /}'比'if(box is int){var value =(int)box;/*使用值* /}'。所以我知道在后面的例子中使用的CIL指令'unbox.any'将会很快,因为不涉及复制。而且,在那些.NET中,只要简单的值始终放在非泛型集合中,就必须快速。 __但它是如何回答我的问题的?__在类型检查失败的“分支”中,我们不能将更多细节放入异常吗? –

+0

此外,'castclass' CIL指令预计会非常快速,并且在那些集合不是强类型的'ArrayList'和'Hashtable'天必须如此快。 'castclass'不复制,只是类型检查和参考去同一个地方。那么区别在哪里?在类型检查失败的情况下,'castclass'会导致在异常消息中拼写出的类型和类型的“丰富”异常。 –

回答

4

TL; DR;

我认为运行时具有改善消息所需的所有信息。也许有些JIT开发人员可以提供帮助,因为不用说JIT代码非常敏感,并且有时候会因为性能或安全原因而作出决定,这对于外人来说是非常难以理解的。

详细解释

为了简化我改变该方法的问题:

C#

void StringBuilderCast() 
{ 
    object sbuilder = new StringBuilder(); 
    string s = (string)sbuilder; 
} 

IL

.method private hidebysig 
    instance void StringBuilderCast() cil managed 
{ 
    // Method begins at RVA 0x214c 
    // Code size 15 (0xf) 
    .maxstack 1 
    .locals init (
     [0] object sbuilder, 
     [1] string s 
    ) 

    IL_0000: nop 
    IL_0001: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor() 
    IL_0006: stloc.0 
    IL_0007: ldloc.0 
    IL_0008: castclass [mscorlib]System.String 
    IL_000d: stloc.1 
    IL_000e: ret 
} // end of method Program::StringBuilderCast 

重要这里操作码为:

http://msdn.microsoft.com/library/system.reflection.emit.opcodes.newobj.aspx http://msdn.microsoft.com/library/system.reflection.emit.opcodes.castclass.aspx

而一般的内存布局是:

Thread Stack      Heap 
+---------------+   +---+---+----------+ 
| some variable | +---->| L | T | DATA | 
+---------------+ |  +---+---+----------+ 
| sbuilder2 |----+ 
+---------------+ 

T = Instance Type 
L = Instance Lock 
Data = Instance Data 

因此,在这种情况下,运行时知道它有一个指向StringBuilder的 ,它应该将它转换为字符串。在这种情况下,它有所有的信息 需要尽可能给你最好的例外。

如果我们在JIT看到 https://github.com/dotnet/coreclr/blob/32f0f9721afb584b4a14d69135bea7ddc129f755/src/vm/interpreter.cpp#L6137 我们将自身类似的东西

CORINFO_CLASS_HANDLE cls = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Casting InterpTracingArg(RTK_CastClass)); 
Object * pObj = OpStackGet<Object*>(idx); 
ObjIsInstanceOf(pObj, TypeHandle(cls), TRUE)) //ObjIsInstanceOf will throw if cast can't be done 

如果我们深入这个方法

https://github.com/dotnet/coreclr/blob/32f0f9721afb584b4a14d69135bea7ddc129f755/src/vm/eedbginterfaceimpl.cpp#L1633

和重要组成部分是:

BOOL fCast = FALSE; 
TypeHandle fromTypeHnd = obj->GetTypeHandle(); 
if (fromTypeHnd.CanCastTo(toTypeHnd)) 
    { 
     fCast = TRUE; 
    } 
if (Nullable::IsNullableForType(toTypeHnd, obj->GetMethodTable())) 
    { 
     // allow an object of type T to be cast to Nullable<T> (they have the same representation) 
     fCast = TRUE; 
    } 
    // If type implements ICastable interface we give it a chance to tell us if it can be casted 
    // to a given type. 
    else if (toTypeHnd.IsInterface() && fromTypeHnd.GetMethodTable()->IsICastable()) 
    { 
    ... 
    } 
if (!fCast && throwCastException) 
    { 
     COMPlusThrowInvalidCastException(&obj, toTypeHnd); 
    } 

这里的重要部分是抛出异常的方法。正如你所看到的 它接收当前对象和你试图转换的类型。

最后,投掷方法调用此方法:

https://github.com/dotnet/coreclr/blob/32f0f9721afb584b4a14d69135bea7ddc129f755/src/vm/excep.cpp#L13997

COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, strCastFromName.GetUnicode(), strCastToName.GetUnicode()); 

至极为您提供了与类型名漂亮的异常信息。

但是当你施放对象为值类型

C#

void StringBuilderToLong() 
{ 
    object sbuilder = new StringBuilder(); 
    long s = (long)sbuilder; 
} 

IL

.method private hidebysig 
    instance void StringBuilderToLong() cil managed 
{ 
    // Method begins at RVA 0x2168 
    // Code size 15 (0xf) 
    .maxstack 1 
    .locals init (
     [0] object sbuilder, 
     [1] int64 s 
    ) 

    IL_0000: nop 
    IL_0001: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor() 
    IL_0006: stloc.0 
    IL_0007: ldloc.0 
    IL_0008: unbox.any [mscorlib]System.Int64 
    IL_000d: stloc.1 
    IL_000e: ret 
} 

重要的操作码在这里:
http://msdn.microsoft.com/library/system.reflection.emit.opcodes.unbox_any.aspx

我们可以看到Unb oxAny行为在这里 https://github.com/dotnet/coreclr/blob/32f0f9721afb584b4a14d69135bea7ddc129f755/src/vm/interpreter.cpp#L8766

//GET THE BOXED VALUE FROM THE STACK 
Object* obj = OpStackGet<Object*>(tos); 

//GET THE TARGET TYPE METADATA 
unsigned boxTypeTok = getU4LittleEndian(m_ILCodePtr + 1); 
boxTypeClsHnd = boxTypeResolvedTok.hClass; 
boxTypeAttribs = m_interpCeeInfo.getClassAttribs(boxTypeClsHnd); 

//IF THE TARGET TYPE IS A REFERENCE TYPE 
//NOTHING CHANGE FROM ABOVE 
if ((boxTypeAttribs & CORINFO_FLG_VALUECLASS) == 0) 
{ 
    !ObjIsInstanceOf(obj, TypeHandle(boxTypeClsHnd), TRUE) 
} 
//ELSE THE TARGET TYPE IS A REFERENCE TYPE 
else 
{ 
    unboxHelper = m_interpCeeInfo.getUnBoxHelper(boxTypeClsHnd); 
    switch (unboxHelper) 
     { 
     case CORINFO_HELP_UNBOX: 
       MethodTable* pMT1 = (MethodTable*)boxTypeClsHnd; 
       MethodTable* pMT2 = obj->GetMethodTable(); 

       if (pMT1->IsEquivalentTo(pMT2)) 
       { 
        res = OpStackGet<Object*>(tos)->UnBox(); 
       } 
       else 
       { 
        CorElementType type1 = pMT1->GetInternalCorElementType(); 
        CorElementType type2 = pMT2->GetInternalCorElementType(); 

        // we allow enums and their primtive type to be interchangable 
        if (type1 == type2) 
        { 
          res = OpStackGet<Object*>(tos)->UnBox(); 
        } 
       } 

     //THE RUNTIME DOES NOT KNOW HOW TO UNBOX THIS ITEM 
       if (res == NULL) 
       { 
        COMPlusThrow(kInvalidCastException); 

        //I INSERTED THIS COMMENTS 
      //auto thCastFrom = obj->GetTypeHandle(); 
      //auto thCastTo = TypeHandle(boxTypeClsHnd); 
      //RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo); 
       } 
       break; 
     case CORINFO_HELP_UNBOX_NULLABLE: 
       InterpreterType it = InterpreterType(&m_interpCeeInfo, boxTypeClsHnd); 
       size_t sz = it.Size(&m_interpCeeInfo); 
       if (sz > sizeof(INT64)) 
       { 
        void* destPtr = LargeStructOperandStackPush(sz); 
        if (!Nullable::UnBox(destPtr, ObjectToOBJECTREF(obj), (MethodTable*)boxTypeClsHnd)) 
        { 
         COMPlusThrow(kInvalidCastException); 
        //I INSERTED THIS COMMENTS 
      //auto thCastFrom = obj->GetTypeHandle(); 
      //auto thCastTo = TypeHandle(boxTypeClsHnd); 
      //RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo); 
        } 
       } 
       else 
       { 
        INT64 dest = 0; 
        if (!Nullable::UnBox(&dest, ObjectToOBJECTREF(obj), (MethodTable*)boxTypeClsHnd)) 
        { 
         COMPlusThrow(kInvalidCastException); 
        //I INSERTED THIS COMMENTS 
      //auto thCastFrom = obj->GetTypeHandle(); 
      //auto thCastTo = TypeHandle(boxTypeClsHnd); 
      //RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo); 
        } 
       } 
      } 
      break; 
     } 
} 

嗯...至少,似乎有可能提供更好的例外信息。 如果你还记得当异常有一个不错的消息电话是:

COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, strCastFromName.GetUnicode(), strCastToName.GetUnicode()); 

和少inforative消息是:

COMPlusThrow(kInvalidCastException); 

所以我认为这是可以提高的消息做

auto thCastFrom = obj->GetTypeHandle(); 
auto thCastTo = TypeHandle(boxTypeClsHnd); 
RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo); 

我在coreclr github上创建了以下问题,以了解Microsoft开发人员的看法。

https://github.com/dotnet/coreclr/issues/7655

+0

感谢您的分析。如果你在Github上创建了一个问题,那就太好了,然后你可以链接到这个Stack Overflow线程,我可以从这里链接到Github。 –

+1

我已经创建了该问题并在此处插入了链接。感谢您的建议。 –

+1

对您的Github问题有一个有趣的评论。我附加了一个更新到我的问题文本。 –

相关问题