如何在对象初始值设定器中指定readonly成员变量? [英] How do I assign a readonly member variable in an object initializer?
本文介绍了如何在对象初始值设定器中指定readonly成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类Foo {
公共只读INT吧;
};
foo的=新的Foo(){栏= 123};
错误CS0191:只读字段不能被分配到(除了在构造函数或变量初始化)
如何分配栏
在上面的对象初始化?
我可以初始化只读成员,而无需编写自定义的构造函数,每类/结构?
解决方案
foo的=新的Foo(){栏= 123};
是由编译器转化为
美孚TEMP =新的Foo();
temp.bar = 123;
foo的=温度;
正如你所看到的,分配给栏
既不在富
构造,也不是一个变量初始化
因此,答案是:你不能。
class foo {
public readonly int bar;
};
foo a = new foo() { bar = 123 };
error CS0191: A readonly field cannot be assigned to (except in a constructor or a variable initializer)
How can I assign bar
in the object initializer above?
Can I initialize readonly members without having to write a custom constructor for every class/struct ?
解决方案
foo a = new foo() { bar = 123 };
is transformed by the compiler to
foo temp = new foo();
temp.bar = 123;
foo a = temp;
As you can see, the assignment to bar
is neither in the foo
constructor nor a variable initializer.
So the answer is: you can't.
这篇关于如何在对象初始值设定器中指定readonly成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文