c# - const, readonly 和 get 在静态类中有什么区别

标签 c#

<分区>

我有一个问题。最近我发现自己使用了 3 行不同的代码,仔细检查它们看起来和感觉都一样。

public static class constant
{
    public static readonly int val1 = 5;
    public const int val2 = 5;
    public static int val3 { get { return 5; } }
}

我的问题是,它们是一样的吗?应该用一个代替另一个吗?如果是这样。什么时候?

在 visual studio 中还有一个额外的问题,为什么它们在 intellisense 中的表示方式不同?

enter image description here

最佳答案

声明为只读的成员提供了在类的(静态)构造函数中更改的可能性,而 const 成员不能在运行时更改。

将字段声明为 const 使其自动静态,引用 §10.3.7:

When a field, method, property, event, operator, or constructor declaration includes a static modifier, it declares a static member. In addition, a constant or type declaration implicitly declares a static member.

第三个只是一个只读属性,恰好总是返回 5。

您永远不应该使用这样的属性,并尽可能使用 const 成员,以允许编译器和/或抖动执行它们的优化并帮助其他人阅读您的代码(该属性对我来说是一种 WTF) .如果需要在程序启动期间初始化的常量值(例如,机器的核心数),则必须使用静态只读成员。

这是 C# 规范 (§10.5.2.1) 中的一个很好的例子:

A static readonly field is useful when a symbolic name for a constant value is desired, but when the type of the value is not permitted in a const declaration, or when the value cannot be computed at compile-time. In the example

public class Color
{
    public static readonly Color Black = new Color(0, 0, 0);
    public static readonly Color White = new Color(255, 255, 255);
    public static readonly Color Red = new Color(255, 0, 0);
    public static readonly Color Green = new Color(0, 255, 0);
    public static readonly Color Blue = new Color(0, 0, 255);
    private byte red, green, blue;
    public Color(byte r, byte g, byte b) {
        red = r;
        green = g;
        blue = b;
    }
}

the Black, White, Red, Green, and Blue members cannot be declared as const members because their values cannot be computed at compile-time. However, declaring them static readonly instead has much the same effect.

还有另一个区别(§10.5.2.2):

Constants and readonly fields have different binary versioning semantics. When an expression references a constant, the value of the constant is obtained at compile-time, but when an expression references a readonly field, the value of the field is not obtained until run-time.

因此,总而言之,即使乍一看它们可能看起来很相似,它们也有很大的不同,您应该使用最适合您意图的那个。

关于c# - const, readonly 和 get 在静态类中有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18578938/

相关文章:

c# - 在 C# 3.0 中缩小 XML 的最佳方法

c# - 我可以在没有上下文的情况下使用实体吗?

C#/XSLT : Linearizing XML partially working code

c# - @: and <text> in Razor 之间的区别

c# - .NET Core RC2 - NeutralResourcesLanguageAttribute

c# - 使用 key A 和 B 读取 Mifare 1k 卡

c# - VB.NET 和 MVC 5 使用具有内置帮助程序且无 App_Code 的自定义帮助程序

c# - 如何从 powershell 脚本获取值到 C# 变量中?

c# - 如何在C#中循环几个dos命令

c# - 为什么不能实例化抽象类,不能实例化的类有什么用