在对象初始化只读字段 [英] Readonly field in object initializer
本文介绍了在对象初始化只读字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道为什么它是不可能做到以下几点:
结构TestStruct
{
公共只读对象TestField;
}
TestStruct TS =新TestStruct {
/ * TestField =东西//不可能* /
};
应该不是对象初始值可以设置字段
的值<? / p>
解决方案
对象初始化内部使用的临时对象,然后分配每个值的属性。有一个只读字段将打破。
随着
TestStruct TS =新TestStruct
{
TestField =东西;
};
将转化为
TestStruct TS;
变种TMP =新TestStruct();
tmp.TestField =东西; //这是不可能的
TS = tmp中;
(这里是的从乔恩斯基特答案解释临时对象与对象initalizer但使用不同的场景的使用)
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 ?
解决方案
Object Initializer internally uses a temporary object and then assign each value to the properties. Having a readonly field would break that.
Following
TestStruct ts = new TestStruct
{
TestField = "something";
};
Would translate into
TestStruct ts;
var tmp = new TestStruct();
tmp.TestField = "something"; //this is not possible
ts = tmp;
(Here is the answer from Jon Skeet explaining the usage of temporary object with object initalizer but with a different scenario)
这篇关于在对象初始化只读字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文