Readonly field in object initializer

2019-06-16 09:56发布

I wonder why it is not possible to do the following:

struct TestStruct
{
    public readonly object TestField;
}

TestStruct ts = new TestStruct {
    /* TestField = "something" // Impossible */
};

Shouldn't the object initializer be able to set the value of the fields ?

标签: c# readonly
7条回答
Deceive 欺骗
2楼-- · 2019-06-16 10:26

Because object initializer is just a short way of initializing:

TestStruct ts = new TestStruct {
  TestField = "something";
};

is the same to (compiler will translate the above to this):

TestStruct ts = new TestStruct();
ts.TestField = "something";//this is of course not allowed.
查看更多
登录 后发表回答