在仅由构造函数调用的私有方法中分配只读变量的值
C# 编译器给了我以下错误
CS0191: 无法将只读字段分配给(构造函数或变量初始值设定项中除外)
我是否必须将代码(在我的私有函数中)移至构造函数中?听起来很尴尬。
请注意,私有方法仅供构造函数调用。我希望有某种属性可以用来标记相应的方法。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不管其他帖子怎么说,实际上有一种(有点不寻常的)方法可以做到这一点,并在方法中实际分配值:
来自 这里。
或者,您也可以从私有方法返回值并在构造函数中分配它,如下所示:
Despite what the other posts are saying, there is actually a (somewhat unusual) way to do this and actually assign the value in a method:
Example derived from here.
Alternatively, you can also return the value from a private method and assign it in the constructor as follows:
只读字段只能由构造函数分配。您可以做的是使用以下方法初始化该字段:
Readonly field can only be assigned by the constructor. What you can do is to initialize the field with a method:
是的。您是否尝试过使用构造函数链作为使用通用方法的替代方法?
Yes. Have you tried constructor chaining as an alternative to using a common method?
readonly
成员只能在类级别或其构造函数中分配。这就是使用readonly
关键字的好处。当使用“除了
string
类”的类时,您可以使用readonly
来替代const
关键字,因为编译器不允许您将const
分配给类。The
readonly
members can only assigned in the class level or on its constructor. that is the benefit from using thereadonly
keyword.You can use
readonly
as alternative to theconst
keyword when using classes "other that thestring
class", because the compiler will not allow you to assign aconst
to a classes.如果你想修改它,你不应该首先将其设置为只读。一旦变量是只读的,您只能在构造函数中或在声明时修改它,如错误所示
根据 MSDN
If you want to modify it you should not make it read only in the first place. Once a variable is read only you can modify it only in constructor or at declaration time as error suggests
According to MSDN
您可以将“{ get; private set; }”粘贴到只读声明中的每个等号前面,以实现几乎相同的效果(属性现在可以在类中的任何位置设置,而不仅仅是在构造函数中,但至少在外部不可更改班级)。对于值类型来说这是严格正确的,但对于只读可能具有优势的引用类型则不然。
You can literally paste "{ get; private set; }" in front of each equals sign in your readonly declarations to achieve almost the same thing (property can now be set in anywhere in class not just in constructor but at least its not changeable outside class). This is strictly true for value types but not reference types in which readonly might have an advantage.