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

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

问题描述

一直在浏览.NET Framework参考源的.NET源码,只是为了好玩.并发现了一些我不明白的东西.

Been browsing through .NET source code of .NET Framework Reference Source, just for fun of it. And found something I don't understand.

有一个 Int32.cs 文件,其中包含 Int32 类型的 C# 代码.不知何故,这对我来说似乎很奇怪.C# 编译器如何为 Int32 类型编译代码?

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;

    // ... 
}

但这在 C# 中不是非法的吗?如果 int 只是 Int32别名,它应该无法使用 错误 CS0523:

But isn't this illegal in C#? If int is only an alias for Int32, it should fail to compile with Error CS0523:

struct1"类型的结构成员struct2 field"导致结构布局出现循环.

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?

推荐答案

这在 C# 中不是非法的吗?如果int"只是Int32"的别名,它应该无法编译并出现错误 CS0523.编译器有什么魔力吗?

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; }

在这种情况下,S 的大小是未定义的,因为无论 S 的大小是多少,它都必须等于自身加上 ​​int 的大小.没有这样的大小.

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; }

在这种情况下,我们没有任何信息可以用来推断 S 的大小.

In that case we have no information from which to deduce the size of S.

struct Int32 { Int32 i; }

但在这种情况下,编译器提前知道 System.Int32 是四个字节,因为它是一种非常特殊的类型.

But in this case the compiler knows ahead of time that System.Int32 is four bytes because it is a very special type.

顺便说一下,C# 编译器(以及就此而言,CLR)如何确定一组结构类型何时为循环的细节非常有趣.我会尝试在某个时候写一篇关于此的博客文章.

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天全站免登陆