Read-only list or unmodifiable list in .NET 4.0

前端 未结 6 1272
清酒与你
清酒与你 2020-12-05 08:58

From what I can tell, .NET 4.0 still lacks read-only lists. Why does the framework still lack this functionality? Isn\'t this one of the commonest pieces of functionality fo

相关标签:
6条回答
  • 2020-12-05 09:36

    How about the ReadOnlyCollection already within the framework?

    0 讨论(0)
  • 2020-12-05 09:45

    For those who like to use interfaces: .NET 4.5 adds the generic IReadOnlyList interface which is implemented by List<T> for example.

    It is similar to IReadOnlyCollection and adds an Item indexer property.

    0 讨论(0)
  • 2020-12-05 09:48

    You're looking for ReadOnlyCollection, which has been around since .NET2.

    IList<string> foo = ...;
    // ...
    ReadOnlyCollection<string> bar = new ReadOnlyCollection<string>(foo);
    

    or

    List<string> foo = ...;
    // ...
    ReadOnlyCollection<string> bar = foo.AsReadOnly();
    

    This creates a read-only view, which reflects changes made to the wrapped collection.

    0 讨论(0)
  • 2020-12-05 09:50

    In 2.0 you can call AsReadOnly to get a read-only version of the list. Or wrap an existing IList in a ReadOnlyCollection<T> object.

    0 讨论(0)
  • 2020-12-05 09:53

    If the most common pattern of the list is to iterate through all the elements, IEnumerable<T> or IQueryable<T> can effectively act as a read-only list as well.

    0 讨论(0)
  • 2020-12-05 10:02

    What's wrong with System.Collections.ObjectModel.ReadOnlyCollection?

    0 讨论(0)
提交回复
热议问题