gpt4 book ai didi

c# - 数组上的 AsEnumerable() 有什么用?

转载 作者:可可西里 更新时间:2023-11-01 08:57:28 24 4
gpt4 key购买 nike

我正在阅读 a blog埃里克·利珀特 (Eric Lippert) 解释了为什么他几乎从不使用数组,以下部分让我很好奇:

If you are writing such an API, wrap the array in a ReadOnlyCollection and return an IEnumerable or an IList or something, but not an array. (And of course, do not simply cast the array to IEnumerable and think you’re done! That is still passing out variables; the caller can simply cast back to array! Only pass out an array if it is wrapped up by a read-only object.)

所以我在收集方面有点乱:

string[] array = new[] { "cat", "dog", "parrot" };
IEnumerable<string> test1 = array.AsEnumerable();
string[] secondArray = (string[])test1;

//array1[0] is now also "whale"
array[0] = "whale";

//11 interfaces
var iArray = array.GetType().GetInterfaces();
//Still 11 interfaces??
var iTest1 = test1.GetType().GetInterfaces();

我初始化一个数组,然后在其上使用 AsEnumerable() 方法将其转换为 IEnumerable(或者我是这么想的),但是当我将其强制转换回到一个新数组,并更改原始数组中的值,test1secondArray 的值已更改为。显然我只是对原始数组进行了 2 个新引用,而不是创建一个新的 IEnumerable 有点像 ToArray() 返回一个新数组。

当我比较数组和IEnumerable 的接口(interface)时,它们都具有相同的接口(interface)。如果数组实际上什么都不做,为什么它有那个方法呢?我知道 AsEnumerable() 与 Linq-to-entities 一起使用,当您有一个 IQueryable 时可以获取可枚举的方法,但是为什么要将此方法添加到一个大批?这种方法有实际用途吗?

编辑:Tim Schmelter 的这条评论提出了一个非常好的观点,不应被忽视:

“它并不是那么无用。您可以在不破坏其余代码的情况下更改实际类型。因此您可以将数组替换为数据库查询或列表或哈希集或其他任何东西,但 AsEnumerable 始终有效并且之后的其余代码。所以 AsEnumerable 就像一个契约(Contract)。”

最佳答案

AsEnumerable只是将值转换为 IEnumerable<T> 的一种方式.它不会创建新对象。该方法的实现如下:

public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source)
{
return source;
}

它根本没有创建新对象。

有用的原因:

  1. 如果一个对象实现了IEnumerable<T>但也有一个名为 Select 的实例方法, Where等,您不能使用 LINQ 方法。 AsEnumerable让你把它转换到IEnumerable以避免此类过载冲突。

  2. 如果你想将一个对象转换为IEnumerable<T> (无论出于何种原因),但是 T是匿名类型,您不能使用强制转换,您需要一个可以推断其通用参数的通用方法来执行此操作。

关于c# - 数组上的 AsEnumerable() 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34203704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com