如果的Int32只是一个别名INT,如何能的Int32类使用int? [英] If Int32 is just an alias for int, how can the Int32 class use an int?

查看:231
本文介绍了如果的Int32只是一个别名INT,如何能的Int32类使用int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

被浏览过 .NET框架参考源的.NET源$ C ​​$ C,只是为了好玩。并发现了一些我不明白。

有一个的 Int32.cs 的用C#code文件的Int32 键入。不知怎的,这似乎很奇怪,我。如何在C#编译器编译code为的Int32 键入?

 公共结构的Int32:IComparable的,IFormattable,IConvertible {
    内部INT m_value;    // ...
}

但不是这种非法在C#中?如果 INT 只是一个的别名的Int32 ,它应该失败,编译<一个HREF =htt​​p://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 for Int32 type?

public struct Int32: IComparable, IFormattable, IConvertible {
    internal int m_value;

    // ... 
}

But isn't this illegal in C#? If int is only an alias for Int32, 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屋!

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