【问题标题】:What is the c# equivalent of public final static in javajava中public final static的c#等价物是什么
【发布时间】:2010-11-13 23:35:48
【问题描述】:

在Java中我可以写:

public final static MyClass foo = new MyClass("foo");

在 C# 中是否有任何等价物?

【问题讨论】:

    标签: c# java static final public


    【解决方案1】:

    我能想到的最接近 Java final 字段的东西(不完全相同,final has other meanings)是 readonly

    public static readonly MyClass field = new MyClass("foo");
    

    如果您有原始类型(字符串、整数、布尔值),您可能希望使用 const

    public const string MAGIC_STRING = "Foo";
    

    【讨论】:

    • 对于字段,它们几乎完全相同。关于初始化有不同的规则(此处无关),有时 Java 中的 final 字段就像 C# 中的 const 字段,但在这种情况下,我认为它们实际上是等效的。
    • 请注意readonlyconst 之间的区别。 const 烘焙值,所以如果你换出一个带有const 值的 DLL,其他使用该值的 DLL 将需要重建才能获得新值。 readonly 是运行时,不需要这个。
    • 所以我们不需要原始类型的“静态”?
    【解决方案2】:
    sealed class finalClass
    {
       ...
    }
    

    【讨论】:

    • 这是一个 class - 这是一个 field
    猜你喜欢
    • 2010-11-22
    • 2011-02-23
    • 2013-05-19
    • 2010-12-07
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多