在C#/。NET为什么为sbyte []一样的byte []不同之处在于它不是? [英] In C#/.NET why is sbyte[] the same as byte[] except that it's not?

查看:115
本文介绍了在C#/。NET为什么为sbyte []一样的byte []不同之处在于它不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在C#/。NET发现一个奇怪的现象。

I just observed a weird phenomenon in C#/.NET.

我创造了这个小例子来演示:

I created this minimal example to demonstrate:

if (new sbyte[5] is byte[])
{
 throw new ApplicationException("Impossible!");
}

object o = new sbyte[5];

if (o is byte[])
{
 throw new ApplicationException("Why???");
}

这将引发为什么?,而不是不可能!。它适用于整数类型相同尺寸的所有阵列。有人可以解释这样对我?我很困惑。我使用.NET 4的方式。

This will throw "Why???", but not "Impossible!". It works for all arrays of integral types of the same size. Can someone explain this to me? I'm confused. I'm using .NET 4 by the way.

P.S:我知道,我可以用得到预期的结果 o.GetType()== typeof运算(字节[])

P.S.: I know that I can get the expected result by using o.GetType() == typeof(byte[]).

推荐答案

铸造的CLR规则规定,这是可能的。 C#的规则,说这是不可能的。 <一href=\"http://blogs.msdn.com/b/ericlippert/archive/2009/09/24/why-is-covariance-of-value-typed-arrays-inconsistent.aspx\">The C#的团队意识地决定,他们会从规范以各种理由容忍这种偏差。

The CLR rules of casting specify that this is possible. The C# rules say it is not possible. The C# team consciously decided that they would tolerate this deviation from the spec for various reasons.

为什么CLR允许这样做?大概是因为他们可以方便地实现它。 字节为sbyte 具有相同的二进制重新presentation这样你就可以治疗一字节[] 为sbyte [] 在不违反内存安全

Why does the CLR allow this? Probably because they can conveniently implement it. byte and sbyte have the same binary representation so you can "treat" a byte[] as an sbyte[] without violating memory safety.

相同的技巧适用于其他基本类型有相同的内存布局。

The same trick works for other primitive types with the same memory layout.

这篇关于在C#/。NET为什么为sbyte []一样的byte []不同之处在于它不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆