Why And how to use static readonly modifier in C#
Well I was been studying about Destructor, which influenced me to constructors once again ... So started some googling and testing than I faced something like this ..
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;
}
}
I made three private attributes of static, readonly, static readonly
As they are private attributes I named them with _prefix. But my resharper telling me to rename _staticReadolyDateTime into StaticReadolyDateTime (ie as it is static readonly, may be). Is it oke with the naming convensions ?
on the other hand I am unable to use the static readonly attribute in public constructor, but using that static and readonly one easily.(ie even using it in static constructor)
than i googled to find out more, most of them are saying static readonly should only used in static constructor but not saying why ?
so I need to know some usages of static readonly modifier and its best uses and limitations. Difference with const, static, readonly will be even better ... :)
A non-static readonly member can only be set in the class or a non-static constructor.
A static readonly member can only be set in the class or a static constructor.
Hence, it is illegal to set a static readonly member in your non-static constructor. Note that there is nothing wrong with reading the static readonly member anywhere you want in the class; the restriction is just on where you can write it. If you don't want the restriction, don't call it readonly
.
readonly can be set only in constructor. Once set, it acts like a constant which cannot be modified. And for static readonly it needs to be set in static constructor.
链接地址: http://www.djcxy.com/p/21084.html上一篇: EventInfo访问修饰符
下一篇: 为什么以及如何在C#中使用静态只读修饰符