【发布时间】:2020-03-28 18:59:48
【问题描述】:
参考源网站上System.Boolean 的源代码指出struct Boolean 的实例仅包含一个bool 字段:private bool m_value:
https://referencesource.microsoft.com/#mscorlib/system/boolean.cs,f1b135ff6c380b37
namespace System {
using System;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Boolean : IComparable, IConvertible
#if GENERICS_WORK
, IComparable<Boolean>, IEquatable<Boolean>
#endif
{
private bool m_value;
internal const int True = 1;
internal const int False = 0;
internal const String TrueLiteral = "True";
internal const String FalseLiteral = "False";
public static readonly String TrueString = TrueLiteral;
public static readonly String FalseString = FalseLiteral;
}
但我注意到了……
-
bool是 a C# language alias 对应于System.Boolean。 - 类型是
struct Boolean,它是一个值类型,意思是it cannot contain itself as a field。 - ...但是这段代码大概可以编译。
- 我知道,当设置了
-nostdlib编译器选项时,您需要提供自己的基本 类型定义,例如System.String、System.Int32、System.Exception- 这是唯一的区别。 - 发布的源代码不包含其他特殊属性,如
[MethodImpl( MethodImplOptions.InternalCall )]。
那么这段代码是如何编译的呢?
【问题讨论】:
-
这是一个很好的证明,常见的“它是一个别名”假设是一个破碎的心智模型。
bool是 C# 语言中的关键字。编译器和运行时都有很多关于类型的内置知识,不需要 System.Boolean 的帮助。 mscorlib 中原始值类型的声明与该类型的装箱表示相匹配。
标签: c#