【问题标题】:Why And how to use static readonly modifier in C#为什么以及如何在 C# 中使用静态只读修饰符
【发布时间】:2013-11-05 19:13:50
【问题描述】:

嗯,我一直在研究析构函数,它再次影响了我对构造函数... 所以开始了一些谷歌搜索和测试,而不是我遇到这样的事情..

public class Teacher
{
    private static DateTime _staticDateTime;
    private readonly DateTime _readOnlyDateTime;
    /*Resharper telling me to name it StaticReadolyDateTime insted of _staticReadolyDateTime*/
    private static readonly DateTime StaticReadolyDateTime;

    static Teacher()
    {
        _staticDateTime = DateTime.Now;
        /*ERROR : Thats oke as _readOnlyDateTime is not static*/
        //_readOnlyDateTime = DateTime.Now;
        StaticReadolyDateTime = DateTime.Now;
    }

    public Teacher()
    {
        _staticDateTime = DateTime.Now;
        _readOnlyDateTime = DateTime.Now;
        /*Error : Why there is an error ?*/
        StaticReadolyDateTime = DateTime.Now;
    }
}

我做了三个私有属性static、readonly、static readonly

因为它们是私有属性,所以我用 _prefix 命名它们。 但是我的 resharper 告诉我将 _staticReadolyDateTime 重命名为 StaticReadolyDateTime (即,它可能是静态只读的)。 命名约定可以吗?

另一方面,我无法在公共构造函数中使用静态只读属性,但可以轻松使用该静态和只读属性。(即即使在静态构造函数中使用它)

比我用谷歌搜索更多,他们中的大多数都说静态只读应该只在静态构造函数中使用,而不是说为什么?

所以我需要知道静态只读修饰符的一些用法及其最佳用途和限制。 与 const、static、readonly 的区别会更好...... :)

【问题讨论】:

  • 大概是说只能在静态构造时修改,并不是说只能在静态构造时使用。
  • 旁注:publicstatic 不是“属性”,而是modifierspublic,以及privateprotectedaccess modifiers。 C#/.Net 中的Attributes 是完全不同的概念。

标签: c# static


【解决方案1】:

非静态只读成员只能在类或非静态构造函数中设置。

静态只读成员只能在类或静态构造函数中设置。

因此,在非静态构造函数中设置静态只读成员是非法的。请注意,读取类中任何你想要的静态只读成员都没有错;限制只是你可以在哪里。如果你不想要这个限制,就不要叫它readonly

【讨论】:

  • ok ...但是为什么要使用这个静态只读字段然后...?
  • @DiponRoy - 如果你能坚持从不使用静态你会好得多......但有时有一些计算的字符串值在进程的生命周期内永远不会改变/ AppDomain(如VersionOfSomeFile)。
【解决方案2】:

只读只能在构造函数中设置。一旦设置,它就像一个无法修改的常量。 而对于静态只读,它需要在静态构造函数中设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 2021-07-06
    • 2011-11-07
    • 2011-09-29
    相关资源
    最近更新 更多