在作为数组 return 的 ICollection 上调用 .toArray() 是引用还是副本?
Does calling .toArray() on an ICollection that is an Array return the reference or a copy?
我正在研究一些扩展方法,需要将输入集合转换为数组。
我想节省内存,所以我只想在绝对必要时创建输入的副本。
我必须做:
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();
}
ToArray
总是 创建一个副本。您的扩展方法与 的行为方式相同。
请注意,类型也有一些微妙之处。考虑这段代码:
string[] x = { "a", "b" };
object[] y = x.ExtMethod<object>();
object[] z = x.ToArray<object>();
现在 y
的执行时类型是 string[]
因为它返回了原始数组 - 但 z
的执行时类型是 object[]
因为它是使用指定的类型参数创建了一个新数组。
我正在研究一些扩展方法,需要将输入集合转换为数组。 我想节省内存,所以我只想在绝对必要时创建输入的副本。
我必须做:
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();
}
ToArray
总是 创建一个副本。您的扩展方法与 的行为方式相同。
请注意,类型也有一些微妙之处。考虑这段代码:
string[] x = { "a", "b" };
object[] y = x.ExtMethod<object>();
object[] z = x.ToArray<object>();
现在 y
的执行时类型是 string[]
因为它返回了原始数组 - 但 z
的执行时类型是 object[]
因为它是使用指定的类型参数创建了一个新数组。