[英]Explicit cast required for Enumerable.Empty<T>
Every example I've read so far (google result/stack question) that expalins the use of "Enumerable.Empty" says that i should be able to use it with an array.到目前为止,我读过的每个示例(谷歌结果/堆栈问题)都解释了“Enumerable.Empty”的使用,说明我应该能够将它与数组一起使用。 The VS compiler however, won't allow me to use it unless i explicitly cast it to the array despite defining the type.
然而,VS 编译器不允许我使用它,除非我明确地将它转换为数组,尽管定义了类型。
Why is this?为什么是这样? (I've seen no reference of the cast being required in the ~20 related stack questions or general google results I've looked at)
(我在大约 20 个相关的堆栈问题或我看过的一般谷歌结果中没有看到需要演员表的参考)
//The internet says this should work, but i get a "Cannot implicitly convert type" error
public byte[] dataA = Enumerable.Empty<byte>();
public string[] dataB = Enumerable.Empty<string>();
//Throws no error, but the cast's requirement is never mentioned
public byte[] dataA = (byte[])Enumerable.Empty<byte>();
public string[] dataB = (string[])Enumerable.Empty<string>();
Enumerable.Empty
generates an empty sequence, not an array. Enumerable.Empty
生成一个空序列,而不是一个数组。
If you want to convert the sequence to an array then you can call ToArray
:如果要将序列转换为数组,则可以调用
ToArray
:
byte[] dataA = Enumerable.Empty<byte>().ToArray();
string[] dataB = Enumerable.Empty<string>().ToArray();
If you really want an empty array then why not say:如果你真的想要一个空数组,那么为什么不说:
byte[] dataA = new byte[0];
string[] dataB = new string[0];
Your casting might work, but this is very much relying on how Empty
is implemented.您的转换可能会起作用,但这在很大程度上取决于
Empty
的实现方式。 It may just return an empty array, or it may return something else that implements IEnumerable
but is empty.它可能只返回一个空数组,或者它可能返回实现
IEnumerable
但为空的其他内容。
You meant Array.Empty<T>
, not Enumerable:你的意思是
Array.Empty<T>
,而不是 Enumerable:
public byte[] dataA = Array.Empty<byte>();
public string[] dataB = Array.Empty<string>();
You can use the ToArray()
Linq method to get an Array<T>
out of your IEnumerable<T>
.您可以使用
ToArray()
Linq 方法从IEnumerable<T>
获取Array<T>
IEnumerable<T>
。 So, as already said, you could create an empty sequence using Enumerable.Empty<T>
and then convert it to an array.因此,如前所述,您可以使用
Enumerable.Empty<T>
创建一个空序列,然后将其转换为数组。
Note that in general the static Array<T>.Empty
is recommended way to create an empty array, if you explicitly need one.请注意,通常静态
Array<T>.Empty
是创建空数组的推荐方法,如果您明确需要的话。
Avoid those casts (byte[])
if you can, they will probably bite you hard in the future.如果可以,请避免使用那些类型转换
(byte[])
,它们将来可能会咬你一口。 Indeed it is not required at all.事实上,它根本不是必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.