我意识到,从 .NET 4.5 开始,ReadOnlyCollection<T>
类实现新接口(interface)IReadOnlyCollection<T>
但我仅限于旧版本的库,它没有这个。
我想知道哪一个更好被认为是最佳实践:
public sealed class OptionA {
/// <summary>
/// Gets a read-only list of numbers.
/// </summary>
public ReadOnlyCollection<int> SomeNumbers {
get { return new ReadOnlyCollection<int>(_someNumbers); }
}
...
}
public sealed class OptionB {
/// <summary>
/// Gets a read-only list of numbers.
/// </summary>
public IList<int> SomeNumbers {
get { return new ReadOnlyCollection<int>(_someNumbers); }
}
...
}
最佳答案
您还可以使用 IEnumerable<T>
- 在这种情况下,它将使您的代码尽可能松散耦合。它还通过 ElementAt<T>
提供随机访问方法,如果实际类型实现 IList<T>
,则该方法的复杂度将为 O(1) :
If the type of source implements
IList<T>
, that implementation is used to obtain the element at the specified index. Otherwise, this method obtains the specified element.
暴露IList<T>
或ReadOnlyCollection<T>
如果您确实想强调可以使用恒定时间复杂度的随机访问这一事实,那么这可能会很有用。决定哪一个实际上取决于特定的场景。
关于.net - 公开 IList<T> 或 ReadOnlyCollection<T> 作为只读属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26616042/