首页 文章

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

提问于
浏览
3

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

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;
    }
}

我做了静态,只读,静态只读的三个私有属性

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

另一方面,我无法在公共构造函数中使用静态readonly属性,但是很容易使用static和readonly属性(即使在静态构造函数中使用它)

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

所以我需要了解静态只读修饰符的一些用法及其最佳用途和局限性 . 与const,static,readonly的区别会更好...... :)

2 回答

  • 3

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

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

    因此,在非静态构造函数中设置静态只读成员是非法的 . 请注意,在类中任何地方读取静态只读成员都没有错;限制只是在你可以写它的地方 . 如果你没有't want the restriction, don' t称之为 readonly .

  • 0

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

相关问题