开发者

Readonly field syntactic shortcut

As we know the code:

using(myDisposable)
{
}

is equivalent of

try
{
   //do something with myDisposable 
}
finally
{
  IDisposable disposable = myDisposable as IDisposable;
  if(disposable != null)
  {
    disposable.Dispose();
  } 
}

and

lock(_locker)
{
}

is equivalent of

Monitor.Enter(_locker);
try
{

}
finally
{

  Monitor.Exit(_locker);
}

What is the equivalent of readonly field?

readonl开发者_如何转开发y object _data = new object();


A readonly object is equivalent to the intialization without readonly. The main difference is that the IL metadat will have the initonly bit set on the field.

Nitpick: Both your expansion of using and lock are incorrect in subtle ways.

The lock version is incorrect because it's expansion depends on the version of the CLR and C# compiler you are using. The C# 4.0 compiler combined with the 4.0 runtime uses the Enter(object, ref bool) pattern instead of plain Enter(object)

The using version is subtly incorrect because it looks a bit closer to this in the finally block

if (disposable != null) {
  ((IDisposable)disposable).Dispose();
}


There isn't one; that is, you can't express a readonly field except with the readonly keyword.

The readonly keyword is a signal to the compiler that the field may only be modified inside the class's constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜