c# – 属性不应返回数组

是的,我知道之前已经讨论了很多次,我阅读了有关这个问题的所有帖子和评论,但似乎仍然无法理解.

MSDN提供的解决此违规的一个选项是在访问属性时返回一个集合(或由集合实现的接口),但显然它无法解决问题,因为大多数集合不是不可变的,也可以改变了.

在这个问题的答案和评论中看到的另一种可能性是使用ReadOnlyCollection封装数组并返回它或它的基本接口(如IReadOnlyCollection),但我不明白这是如何解决性能问题的.

如果在任何时候引用该属性,它需要为封装数组的新ReadOnlyCollection分配内存,那么与返回原始副本相比,有什么区别(以性能问题的方式,不是编辑数组/集合)阵列?

此外,ReadOnlyCollection只有一个带有IList参数的构造函数,因此需要在创建数据之前用数据包装数组.

如果我故意想在我的类中使用数组(而不是作为不可变集合),那么当我为ReadOnlyCollection分配新内存并用它封装我的数组而不是返回数组的副本时,性能是否更好?

请澄清一下……

解决方法

If at any time the property is referenced it needs to allocate memory for a new ReadOnlyCollection that encapsulates the array,so what is the difference (in a manner of performance issues,not editing the array/collection) than simply returning a copy of the original array?

ReadOnlyCollection< T>包装集合 – 它不会复制集合.

考虑:

public class Foo
{
    private readonly int[] array; // Initialized in constructor

    public IReadOnlyList<int> Array => array.ToArray(); // copy
    public IReadOnlyList<int> Wrapper => new ReadOnlyCollection<int>(array); // Wrap
}

想象一下,你的数组包含一百万个条目.考虑一下Array属性必须做的工作量 – 它需要获取所有百万条目的副本.考虑Wrapper属性必须完成的工作量 – 必须创建一个只包含引用的对象.

此外,如果你不介意额外的内存命中,你可以做一次:

public class Foo
{
    private readonly int[] array; // Initialized in constructor
    private readonly IReadOnlyList<int> Wrapper { get; }

    public Foo(...)
    {
        array = ...;
        Wrapper = new ReadOnlyCollection<int>(array);
    }
}

现在访问Wrapper属性根本不涉及任何分配 – 如果所有调用者都看到相同的包装器并不重要,因为它们不能改变它.

相关文章

C#项目进行IIS部署过程中报错及其一般解决方案_c#iis执行语句...
微信扫码登录PC端网站应用的案例(C#)_c# 微信扫码登录
原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...