.net - 公开 IList<T> 或 ReadOnlyCollection<T> 作为只读属性?

标签 .net mono readonly-collection

我意识到,从 .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/

相关文章:

c# - LINQ GroupBy 极慢

c# - 将 char 隐式转换为整数有什么好处?

c# - youtube api使用oauth token 在.NET中获取有关用户的信息

build - Mono 3.0.0 基于 CentOS 6 构建

c# - 在 Xamarin.Mac 应用程序中填充 SourceList

c# - 为什么我收到错误 : "cannot implicitly convert type System.Collections.Generic.List"

C#、SynchronizedReadOnlyCollection 及其构造函数

c# - 用于公开成员集合的 ReadOnlyCollection 或 IEnumerable?

c# - 调试 c# 托管应用程序 : how to set a breakpoint when it opens a file

.net - 在线 .NET IDE?