开发者

Compiler-Implemented Immutability in .Net

Given this class...

public class Test
{
开发者_运维知识库  private long _id;

  public Test(long id)
  {
    _id = id;
  }
}

Will the .Net compiler actually compile it as...

public class Test
{
  private readonly long _id;

  public Test(long id)
  {
    _id = id;
  }
}

In other words, does it understand that _id is only ever set from the constructor and is, therefore, readonly?


No, the compiler does not do that. The IL code for the field will be like this:

.field private int64 _id

...while a readonly version would get this IL code:

.field private initonly int64 _id


The compiler cannot possibly know that a field is set only in the constructor. Imagine for example using reflection in some method where the name of the field is read from a database. You need to explicitly specify the readonly keyword if you want the field to be immutable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜