简体   繁体   中英

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++ Example:

List<const Content> listWithConstContent;

The List<T> class in the .NET framework is mutable. There is no equivalent of that C++ feature either in C#, or the CLR.

If you want an immutable list, then you need to use eg 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. 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#不支持那样的不变性

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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