c# - 为什么以及如何在 C# 中使用静态只读修饰符

标签 c# static

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

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三个私有(private)属性

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

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

我用谷歌搜索发现更多,他们中的大多数人都说静态只读应该只用于静态构造函数但没有说明为什么?

所以我需要了解 static readonly 修饰符的一些用法及其最佳用途和限制。 与 const、static、readonly 的区别会更好……:)

最佳答案

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

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

因此,在非静态构造函数中设置静态只读成员是非法的。请注意,读取静态只读成员在类中任何您想要的地方都没有错;限制只是在您可以编写的地方。如果您不想要限制,请不要将其命名为 readonly

关于c# - 为什么以及如何在 C# 中使用静态只读修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19796932/

相关文章:

c# - 如何让一个简单的超链接在 XAML 中工作?

c# - 回发时 MVC 列表为空

c# - Html Agility Pack 无法使用 xpath 找到列表选项

flutter - 如何在 dart/flutter 中继承静态方法?

java - 安卓工作室。从其他 Activity 调用静态方法

接口(interface)中的 Java 静态方法/字段(再次!)

c# - 如何向 Image 类等内容添加基本属性?

c# - IEnumerable 在底层与 IObservable 有何不同?

C++11静态函数成员变量

java - 如何在Java中为父类设置计数器而不让子类访问计数器?