如果的Int32只是一个别名INT,如何能的Int32类使用int? [英] If Int32 is just an alias for int, how can the Int32 class use an int?
问题描述
被浏览过 .NET框架参考源的.NET源$ C $ C,只是为了好玩。并发现了一些我不明白。
有一个的 Int32.cs 的用C#code文件的Int32
键入。不知怎的,这似乎很奇怪,我。如何在C#编译器编译code为的Int32
键入?
公共结构的Int32:IComparable的,IFormattable,IConvertible {
内部INT m_value; // ...
}
但不是这种非法在C#中?如果 INT
只是一个的别名的的Int32
,它应该失败,编译<一个HREF =http://msdn.microsoft.com/library/7b625z82.aspx>错误CS0523 :
结构成员类型'struct1的struct2领域'会导致在结构布局一个周期。
块引用>有没有在编译器中一些魔法,还是我完全偏离了轨道?
解决方案
这不就是违法的C#?如果INT只是别名的Int32应该失败,出现错误CS0523编译。有没有在编译一些魔法?
块引用>是的;错误是在编译器pssed故意燮$ P $。循环检查完全跳过,如果有问题的类型是一个内置型
通常这种事情是违法的:
的struct {S S; INT I; }
在这种情况下,S的尺寸是不确定的,因为无论大小S,则它必须等于本身加上int的大小。有没有这样的规模。
的struct {S S; }
在这种情况下,我们没有从中推断S的大小的信息。
结构的Int32 {我的Int32; }
但在这种情况下,编译器知道提前时间
System.Int32
是四个字节,因为这是一个很特殊的类型。顺便说一下,如何在C#编译器(和,对于这个问题,该CLR)决定当一组结构类型是循环的细节是非常有趣。我会尝试在某个时候写一个博客文章。
Been browsing through .NET source code of .NET Framework Reference Source, just for fun of it. And found something I don't understand.
There is a Int32.cs file with C# code for
Int32
type. And somehow that seems strange to me. How does the C# compiler compile code forInt32
type?public struct Int32: IComparable, IFormattable, IConvertible { internal int m_value; // ... }
But isn't this illegal in C#? If
int
is only an alias forInt32
, it should fail to compile with Error CS0523:Struct member 'struct2 field' of type 'struct1' causes a cycle in the struct layout.
Is there some magic in the compiler, or am I completely off track?
解决方案isn't this illegal in C#? If "int" is only alias for "Int32" it should fail to compile with error CS0523. Is there some magic in the compiler?
Yes; the error is deliberately suppressed in the compiler. The cycle checker is skipped entirely if the type in question is a built-in type.
Normally this sort of thing is illegal:
struct S { S s; int i; }
In that case the size of S is undefined because whatever the size of S is, it must be equal to itself plus the size of an int. There is no such size.
struct S { S s; }
In that case we have no information from which to deduce the size of S.
struct Int32 { Int32 i; }
But in this case the compiler knows ahead of time that
System.Int32
is four bytes because it is a very special type.Incidentally, the details of how the C# compiler (and, for that matter, the CLR) determines when a set of struct types is cyclic is extremely interesting. I'll try to write a blog article about that at some point.
这篇关于如果的Int32只是一个别名INT,如何能的Int32类使用int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!