【问题标题】:Explicit cast required for Enumerable.Empty<T>Enumerable.Empty<T> 需要显式转换
【发布时间】:2020-07-14 12:06:52
【问题描述】:

到目前为止,我读过的每个示例(谷歌结果/堆栈问题)都说明了“Enumerable.Empty”的使用,都说我应该能够将它与数组一起使用。然而,VS 编译器不允许我使用它,除非我在定义类型的情况下将其显式转换为数组。

这是为什么? (我在大约 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>();

【问题讨论】:

  • 你能发一个 ling 到它说这应该工作的地方吗?

标签: c# arrays enumerable


【解决方案1】:

Enumerable.Empty 生成一个空序列,而不是一个数组。

如果要将序列转换为数组,则可以调用ToArray:

byte[] dataA = Enumerable.Empty<byte>().ToArray();
string[] dataB = Enumerable.Empty<string>().ToArray(); 

如果你真的想要一个空数组,那为什么不说:

byte[] dataA = new byte[0];
string[] dataB = new string[0];

您的投射可能会起作用,但这在很大程度上取决于Empty 的实现方式。它可能只返回一个空数组,也可能返回实现了IEnumerable 但为空的其他东西。

【讨论】:

    【解决方案2】:

    您的意思是 Array.Empty&lt;T&gt;,而不是 Enumerable:

    public byte[] dataA = Array.Empty<byte>();
    public string[] dataB = Array.Empty<string>(); 
    

    【讨论】:

      【解决方案3】:
      1. 您可以使用ToArray() Linq 方法从您的IEnumerable&lt;T&gt; 中获取Array&lt;T&gt;。因此,如前所述,您可以使用Enumerable.Empty&lt;T&gt; 创建一个空序列,然后将其转换为数组。

      2. 请注意,通常静态 Array&lt;T&gt;.Emptyrecommended way 以创建一个空数组,如果您明确需要的话。

      3. 如果可以的话,请避免使用(byte[]),它们将来可能会狠狠地咬你。事实上,它根本不需要。

      【讨论】:

        猜你喜欢
        • 2011-02-11
        • 1970-01-01
        • 2011-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-29
        • 1970-01-01
        • 2014-02-01
        相关资源
        最近更新 更多