为什么在 boolean 类型中有两个字段具有相同的值?
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;
public static readonly string FalseString;
static Boolean()
{
TrueString = "True";
FalseString = "False";
}
在反射器生成的代码中,方法不使用这些字符串,但是:
public string ToString(IFormatProvider provider)
{
if (!this)
{
return "False";
}
return "True";
}
使用这些常量值不是更好吗?
编辑:在 CIL 中,使用常量字符串和实例字符串没有区别。
所以当我声明一个 private const string = "a"时,在应用程序中任何使用 "a"的地方,Jitter 都使用 const 值,还是仅在 const string 的范围内?
最佳答案
A quick synopsis on the differences between 'const' and 'readonly' in C#:
const:
- Can't be static.
- Value is evaluated at compile time.
- Initiailized at declaration only.
readonly:
- Can be either instance-level or static.
- Value is evaluated at run time.
- Can be initialized in declaration or by code in the constructor.
( source )
因此,在您看到“False”硬编码的地方,它只是在编译时从 FalseLiteral const 替换。
关于.net - 为什么 .NET Boolean 有 TrueLiteral 和 TrueString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2584224/