简体   繁体   English

如何创建具有const内容的C#列表?

[英]How to create a C# List with const content?

In C#: Is there a way to define the content of a List const/readonly like in C++? 在C#中:是否可以像在C ++中那样定义List const / readonly的内容?

C++ Example: C ++示例:

List<const Content> listWithConstContent;

The List<T> class in the .NET framework is mutable. .NET框架中的List<T>类是可变的。 There is no equivalent of that C++ feature either in C#, or the CLR. C#或CLR中都没有等效的C ++功能。

If you want an immutable list, then you need to use eg ImmutableList<T> 如果您想要一个不可变列表,则需要使用例如ImmutableList<T>

Read-only and immutable are different properties. 只读不可变是不同的属性。 Which one do you expect? 您期望哪一个?

  • If you need readonlyness, there is no support for it from C# type system. 如果需要只读,则C#类型系统不支持它。 You need to expose your object through interface that does not allow to mutate state of this object. 您需要通过不允许更改该对象状态的接口公开您的对象。
  • If you need immutability, you need to design your class to work that way. 如果需要不变性,则需要设计类以这种方式工作。 There is no way to make it magically immutable. 没有办法使它神奇不可改​​变。

C#不支持那样的不变性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM