Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

c# - List<T>.AsReadOnly() vs IReadOnlyCollection<T>

List<T> implements IReadOnlyCollection<T> interface and provides the AsReadOnly() method which returns ReadOnlyCollection<T> (which in turn implements IReadOnlyCollection<T>).

What is the usage/reason for AsReadyOnly()? Its existence smells of one or two edge cases where just returning the list as IReadOnlyCollection<T> is just not good enough.

At first I though it may be to prevent casting the cost-ness away but it looks like you can do that with ReadOnlyCollection<T>'s Items accessor.

BTW. The documentation for ReadOnlyCollection<T> type reads

Provides the base class for a generic read-only collection.

which, in my head, conflicts with having a constructor described as

Initializes a new instance of the (...) class that is a read-only wrapper around the specified list.

Update: I did not see that ReadOnlyCollection<T>'s Items is protected.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you just return an actual List<T> as an IReadOnlyList<T>, then the caller can always just cast it back, and then modify the list as they please. Conversely, calling AsReadOnly() creates a read-only wrapper of the list, which consumers can't update.

Note that the read-only wrapper will reflect changes made to the underlying list, so code with access to the original list can still update it with the knowledge that any consumers of the read-only version will see those changes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...