【问题标题】:Does calling .toArray() on an ICollection that is an Array return the reference or a copy? [duplicate]在作为数组的 ICollection 上调用 .toArray() 会返回引用还是副本? [复制]
【发布时间】:2016-11-18 09:26:55
【问题描述】:

我正在研究一些需要将输入集合转换为数组的扩展方法。 我想节省内存,所以我只想在绝对必要时创建输入的副本。

我必须这样做吗:

 public static ICollection<TSource> ExtMethod<TSource>(this ICollection<TSource> source, Func<TSource, int> predicate)
    {
        TSource[] converted;
        if (source is TSource[])
        {
            converted = source as TSource[];
        }
        else {
            converted = source.ToArray();
        }

    }

或者 toArray 是否在幕后进行检查,如果我这样做,我会得到完全相同的效果:

  public static ICollection<TSource> ExtMethod<TSource>(this ICollection<TSource> source, Func<TSource, int> predicate)
    {
        TSource[] converted = source.ToArray();
    }

【问题讨论】:

标签: c# arrays casting extension-methods


【解决方案1】:

ToArray 总是 创建一个副本。您的扩展方法确实不表现相同。

请注意,这里也有关于类型的微妙之处。考虑这段代码:

string[] x = { "a", "b" };
object[] y = x.ExtMethod<object>();
object[] z = x.ToArray<object>();

现在y 的执行时间类型是string[],因为它返回了原始数组 - 但z 的执行时间类型是object[],因为它创建了一个新数组指定参数。

【讨论】:

    猜你喜欢
    • 2012-10-03
    • 2012-04-19
    • 2023-03-10
    • 1970-01-01
    • 2014-03-08
    • 2013-07-06
    • 2011-12-29
    • 2011-02-10
    • 1970-01-01
    相关资源
    最近更新 更多