只读字段语法快捷方式

发布于 2024-10-06 00:10:00 字数 544 浏览 2 评论 0原文

正如我们所知,代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北风几吹夏 2024-10-13 00:10:00

只读对象相当于没有readonly的初始化。主要区别在于 IL 元数据将在该字段上设置 initonly 位。

挑剔:您对 usinglock 的扩展在一些微妙的方面都是不正确的。

lock 版本不正确,因为它的扩展取决于您使用的 CLR 和 C# 编译器的版本。 C# 4.0 编译器与 4.0 运行时相结合,使用 Enter(object, ref bool) 模式,而不是普通的 Enter(object)

using 版本有点不正确,因为它在finally块中看起来更接近于此

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

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();
}
扛起拖把扫天下 2024-10-13 00:10:00

没有一个;也就是说,除非使用 readonly 关键字,否则您无法表达 readonly 字段。

readonly 关键字向编译器发出信号,表明该字段只能在类的构造函数内修改。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文