只读字段语法快捷方式
正如我们所知,代码:
using(myDisposable)
{
}
等价于
try
{
//do something with myDisposable
}
finally
{
IDisposable disposable = myDisposable as IDisposable;
if(disposable != null)
{
disposable.Dispose();
}
}
和
lock(_locker)
{
}
等价于
Monitor.Enter(_locker);
try
{
}
finally
{
Monitor.Exit(_locker);
}
readonly
字段等价于什么?
readonly object _data = new object();
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?
readonly object _data = new object();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只读对象相当于没有
readonly
的初始化。主要区别在于 IL 元数据将在该字段上设置 initonly 位。挑剔:您对
using
和lock
的扩展在一些微妙的方面都是不正确的。lock
版本不正确,因为它的扩展取决于您使用的 CLR 和 C# 编译器的版本。 C# 4.0 编译器与 4.0 运行时相结合,使用Enter(object, ref bool)
模式,而不是普通的Enter(object)
using
版本有点不正确,因为它在finally块中看起来更接近于此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
andlock
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 theEnter(object, ref bool)
pattern instead of plainEnter(object)
The
using
version is subtly incorrect because it looks a bit closer to this in the finally block没有一个;也就是说,除非使用
readonly
关键字,否则您无法表达readonly
字段。readonly 关键字向编译器发出信号,表明该字段只能在类的构造函数内修改。
There isn't one; that is, you can't express a
readonly
field except with thereadonly
keyword.The
readonly
keyword is a signal to the compiler that the field may only be modified inside the class's constructor.