【问题标题】:Casting an Enumerable.Empty<>() into another class that implements IEnumerable returns null将 Enumerable.Empty<>() 转换为另一个实现 IEnumerable 的类返回 null
【发布时间】:2020-11-05 23:14:06
【问题描述】:

我有一个实现 IEnumerable 的类:

public class A { }
public class B : IEnumerable<A> { } 

在这种情况下,我如何将 B 类用作 Enumerable.Empty&lt;A&gt;()? 我的意思是像 Enumerable.Empty&lt;A&gt;() as B 这样的转换返回 null。为什么会这样?我应该实现任何特定的构造函数或方法吗?或者这是一项禁止的操作,我应该以其他方式进行?

【问题讨论】:

  • 您可能想阅读 Eric Lippert 在representation and identity 上的帖子,并确定您认为自己正在尝试进行哪种类型的转换。然后考虑是否任何任意 IEnumerable&lt;A&gt;,包括可能具有类似于Bs 的声明的任何其他类,也应该可以转换为B

标签: c# collections casting ienumerable .net-framework-4.8


【解决方案1】:

Enumerable.Empty&lt;T&gt;()implemented as

internal class EmptyEnumerable<T>
{
    public static readonly T[] Instance = new T[0];
}

public static IEnumerable<T> Empty<T>()
{
    return EmptyEnumerable<T>.Instance;
}

如果您删除优化以缓存空数组,您可以将其重写为:

public static IEnumerable<T> Empty<T>()
{
    return new T[0];
}

所以Enumerable.Empty&lt;T&gt;() 只返回一个T 类型的空数组。

你不会写:

B b = new A[0];

这没有意义:B 不是A 实例的数组。

同理,你不能写:

B b = Enumerable.Empty<A>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多