【发布时间】: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 的区别会更好...... :)
【问题讨论】:
-
大概是说只能在静态构造时修改,并不是说只能在静态构造时使用。
-
旁注:
public、static不是“属性”,而是modifiers。public,以及private和protected是access modifiers。 C#/.Net 中的Attributes 是完全不同的概念。