unbox.any'不提供一个有用的异常文本'castclass'所做的事
本文关键字:异常 有用 文本 一个 castclass any unbox | 更新日期: 2023-09-27 18:12:10
为了说明我的问题,考虑这些简单的例子(c#):
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'。
经验证据表明,对于需要处理问题的(有经验的或没有经验的)开发人员(bug修复者)来说,此文本消息通常非常有帮助。
相反,当尝试开箱(unbox.any
)失败时,我们得到的消息是相当无信息的。有什么技术上的原因为什么必须这样吗?
指定的类型转换无效。(没有什么帮助)
换句话说,为什么我们没有收到这样的消息(我的话):
无法将类型为"X"的对象解盒为类型为"Y"的值;这两种类型必须一致
分别(我的原话):
无法将空引用解框为不可空类型'Y'的值。
所以重复我的问题:在一种情况下错误消息是好的和信息丰富的,而在另一种情况下是糟糕的,这是"偶然的"吗?或者是否存在技术原因导致运行时不可能或极其困难地提供在第二种情况下遇到的实际类型的详细信息?
(我在SO上看到了几个线程,我确信永远不会被问到失败的拆箱异常文本是否更好)
更新:Daniel Frederico Lins Leite的回答导致他在CLR Github上打开了一个问题(见下文)。这被发现是早期问题的重复(由Jon Skeet提出,人们几乎猜到了!)所以没有什么好理由出现糟糕的异常消息,而且人们已经在CLR中修复了它。所以我不是第一个想到这个的人。我们可以期待这一改进在。net框架中发布的那一天。
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.aspxhttp://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的指针它应该把它转换成一个字符串。在这种情况下,它有所有的信息需要给你最好的例外。
如果我们看到JIThttps://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);
}
这里重要的部分是抛出异常的方法。如你所见它同时接收当前对象和您试图强制转换为的类型。
在最后,Throw方法调用这个方法:
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
,我们可以在这里看到UnboxAny行为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());
和信息较少的信息:
COMPlusThrow(kInvalidCastException);
所以我认为这是有可能改善消息做
auto thCastFrom = obj->GetTypeHandle();
auto thCastTo = TypeHandle(boxTypeClsHnd);
RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo);
我在coreclr github上创建了以下问题,看看微软开发人员的意见。
https://github.com/dotnet/coreclr/issues/7655