C# 公共变量在类内可写,但在类外只读
我有一个 .Net C# 类,我需要将变量公开。我需要在方法中(而不是在构造函数中)初始化此变量。但是,我不希望其他类可以修改该变量。这可能吗?
I have a .Net C# class where I need to make a variable public. I need to initialize this variable within a method (not within the constructor). However, I don't want the variable to be modifieable by other classes. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
不要使用字段 - 使用属性:
在此示例中,
Foo.Bar
在任何地方都可读,并且只能由Foo
本身的成员写入。附带说明一下,此示例使用版本 3 中引入的 C# 功能,称为“自动实现的属性”。这是语法糖,编译器将其转换为具有私有支持字段的常规属性,如下所示:
Don't use a field - use a property:
In this example
Foo.Bar
is readable everywhere and writable only by members ofFoo
itself.As a side note, this example is using a C# feature introduced in version 3 called automatically implemented properties. This is syntactical sugar that the compiler will transform into a regular property that has a private backing field like this:
为此,您必须使用属性。如果您对自动 getter/setter 实现感到满意,那么这将起作用:
请注意,无论如何您都不应该将字段公开为公共字段,除非在某些有限的情况下。请改用属性。
You have to use a property for this. If you are fine with an automatic getter/setter implementation, this will work:
Note that you should not expose fields as public anyway, except in some limited circumstances. Use a property instead.
当然。将其设置为属性,并将 setter 设置为私有:
然后设置它(从类中的某个方法中):
Sure. Make it a property, and make the setter private:
Then to set it (from within some method in the class):
使用私有变量并公开公共属性。
Use a private variable and expose a public property.
您不允许为此使用财产吗?如果您是:
Are you not allowed to use a property for this? If you are:
只要您不使用引用类型,到目前为止的答案就很好用。否则,您仍然可以操纵该变量的内部结构。
例如:
This will result in the console output:
这可能正是您想要的,因为您无法更改 SomeBar 但如果您想让变量的内部不可修改,您需要传回变量的副本,例如:
which will result in the output:
请参阅评论了解我添加第三个示例的原因:
The answers so far work good as long as you dont use reference types. Otherwise you will still be able to manipulate the internals of that variable.
e.g:
This will result in the console output:
Which may be exactly what you want as you wont be able to change SomeBar but if you want to make the internals of the variable unmodifiable you need to pass back a copy of the variable, e.g.:
which will result in the output:
See comments for why I added the third example:
Necro 当然可以,但这还不用说 6.0 中语言的改进
Necro for sure, but this bares mentioning with the improvements to the language in 6.0
将其定义为私有?这就是您所要求的,您可以在容器类内的任何位置修改它,但不能在它之外
Define it as private? Is that what you asking for, you can modify it any where inside the container class but you can't out side it