如何在 C# 中声明可写的常量对象数组?
我需要能够设置数组中的对象,但我不希望能够更改任何单个对象的状态。
I need to be able to set the objects in the array, but I don't want to be able to change the state of any of the individual objects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
恐怕你不能。 C# 中没有与 C++ 中的灵活“const”等效的东西。
如果它是您自己的类型,您可以尝试使其不可变(如
string
)。这对于更改非常有效:)请注意,虽然您的问题要求一个可写数组,但实际上没有其他类型 - 您无法创建一个在最初填充时为只读的数组...您必须使用其他一些数组方法(例如,创建一个
ReadOnlyCollection
来包装另一个仅包装器已知的集合)。我知道这对于您的具体情况来说不是问题,但我只是想指出这一点。如果您使变量引用数组只读,则只会阻止其他代码将变量的值设置为对另一个数组的引用 - 它不会阻止数组本身内的更改。You can't, I'm afraid. There's no equivalent of the flexible "const" from C++ in C#.
If it's your own type, you could try to make it immutable (like
string
) to start with though. That would be pretty effective against changes :)Note that although your question asks for a writable array, there's actually no other kind - you can't create an array which is read-only when initially populated... you have to use some other approach (e.g. creating a
ReadOnlyCollection<T>
wrapping another collection which is only known to the wrapper). I know this isn't a problem in your particular case, but I just thought I'd point it out. If you make the variable referring to the arrayreadonly
, that only prevents other code from setting the value of the variable to a reference to another array - it doesn't prevent changes within the array itself.好吧,您可以声明一个私有变量,然后声明一个引用该变量的属性,仅定义 getter,这样就使其只读。
例子:
Well, you can declare a private variable and then declare a property referencing the variable with only getter defined, that sort of makes it read only.
Example:
我会考虑使用某种形式的不可变集合作为更好的设计概念。
选项包括返回为 IEnumerable、使用 Yield[1] 的 IEnumerable、ReadOnlyCollection...请参阅下面的链接以获得更好的解释。
[1]
请参阅http ://geekswithblogs.net/BlackRabbitCoder/archive/2010/11/04/c.net-fundamentals-returning-an-immutable-collection.aspx
I would look into using some form of Immutable collection as a better design concept.
Options include returning as IEnumerable, IEnumerable using yield[1], ReadOnlyCollection... See link down below for better explanation.
[1]
See http://geekswithblogs.net/BlackRabbitCoder/archive/2010/11/04/c.net-fundamentals-returning-an-immutable-collection.aspx