问题描述
有人可以澄清C#是
关键字请。特别是,这些2个问题:
Can somebody clarify the C# is
keyword please. In particular these 2 questions:
Q1)5号线;为什么这回是真的吗?
Q1) line 5; Why does this return true?
Q2)7号线;为什么没有强制转换异常?
Q2) line 7; Why no cast exception?
public void Test()
{
object intArray = new int[] { -100, -200 };
if (intArray is uint[]) //why does this return true?
{
uint[] uintArray = (uint[])intArray; //why no class cast exception?
for (int x = 0; x < uintArray.Length; x++)
{
Console.Out.WriteLine(uintArray[x]);
}
}
}
MSDN的描述不明确的情况。它指出,是
将返回true,如果这些条件得到满足。 (http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx>MDSN条)
MSDN's description does not clarify the situation. It states that is
will return true if either of these conditions are met. (http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx>MDSN Article)
expression is not null.
expression can be cast to type.
我不相信,你可以做INT []的有效铸入UINT []。这是因为:
I don't believe that you can do a valid cast of int[] into uint[]. Because:
A)这code不能编译:
A) This code does not compile:
int[] signed = new int[] { -100 };
uint[] unsigned = (uint[])signed;
B)做在调试器中投给出了一个错误:
B) Doing the cast in the debugger gives an error:
(uint[])signed
"Cannot convert type 'int[]' to 'uint[]'"
果然,如果第3行是为int [],而不是对象,然后它永远不会编译。这使我与Q2最后一个问题。
Sure enough, if line 3 was int[] instead of object then it would never compile. Which brings me to a final question related to Q2.
Q3)为什么C#提高铸件/转换错误调试器,编译器,但是在运行时不会?
Q3) Why does C# raise a cast/conversion error in the debugger and compiler but not at runtime?
推荐答案
C#和CLR有稍有不同的转换规则。
C# and the CLR have somewhat different conversion rules.
您不能的直接的投之间的 INT []
和 UINT []
在C#中,因为语言的不相信任何转换是可用的。然而,如果你通过去对象
,结果是到CLI。从CLI规范第8.7(我希望 - 我引述email交流我对这个话题埃里克利珀的前一段时间):
You can't directly cast between int[]
and uint[]
in C# because the language doesn't believe any conversion is available. However, if you go via object
the result is up to the CLI. From the CLI spec section 8.7 (I hope - I'm quoting an email exchange I had on this topic with Eric Lippert a while ago):
符号和无符号整数主
类型可以被分配给彼此;
例如,INT8:= UINT8是有效的。为了这
目的,布尔应被视为
与 UINT8
,反之亦然兼容,
这使得 BOOL:= UINT8
有效,
反之亦然。这也是真正的
阵列的符号和无符号整数
原始类型相同的大小;
例如, INT32 []:= UINT32 []
是有效的
(我没有检查,但我认为这样的引用类型转换为有效的是什么使是
回也是如此。)
(I haven't checked, but I assume that this sort of reference type conversion being valid is what makes is
return true as well.)
这有点不幸的是,有语言和底层的执行引擎之间的脱节,但它是pretty从长远来看多是不可避免的,我怀疑。还有一些其他的情况下,像这样,但好消息是,他们似乎很少造成显著伤害。
It's somewhat unfortunate that there are disconnects between the language and the underlying execution engine, but it's pretty much unavoidable in the long run, I suspect. There are a few other cases like this, but the good news is that they rarely seem to cause significant harm.
编辑:正如马克删除他的回答,我已经联系到埃里克邮件全部内容,作为发布到C#新闻组
As Marc deleted his answer, I've linked to the full mail from Eric, as posted to the C# newsgroup.
这篇关于并与QUOT为什么,INT []是UINT [] ==真&QUOT;在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!