简体   繁体   English

将 Enumerable.Empty<>() 转换为另一个实现 IEnumerable 的 class 会返回 null

[英]Casting an Enumerable.Empty<>() into another class that implements IEnumerable returns null

I have a class that implements IEnumerable:我有一个实现 IEnumerable 的 class:

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

How can i use class B as Enumerable.Empty<A>() in this case?在这种情况下,我如何使用 class B 作为Enumerable.Empty<A>() I mean that casting like this Enumerable.Empty<A>() as B returns null.我的意思是像这样Enumerable.Empty<A>() as B转换返回 null。 Why it does?为什么会这样? Should i implement any specific constructor or a method?我应该实现任何特定的构造函数或方法吗? Or is it an forbidden operation and I should to do it in the other way?还是这是一项禁止的操作,我应该以其他方式进行操作?

Enumerable.Empty<T>() is implemented as : Enumerable.Empty<T>() 实现为

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

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

If you remove the optimization to cache the empty array, you could rewrite this as:如果您删除优化以缓存空数组,您可以将其重写为:

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

So Enumerable.Empty<T>() just returns an empty array of type T .所以Enumerable.Empty<T>()只返回一个T类型的空数组。

You wouldn't write:你不会写:

B b = new A[0];

This doesn't make sense: a B isn't an array of instances of A .这没有任何意义: a B不是A的实例数组。

For the same reason, you can't write:出于同样的原因,你不能写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM