加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将子类的枚举器强制转换为父类的枚举数是错误的吗?

发布时间:2020-12-16 01:29:09 所属栏目:百科 来源:网络整理
导读:我的构建中出现错误,其中说: Error 12 Cannot implicitly convert type ‘System.Collections.Generic.IEnumerator BaseClass’ to ‘System.Collections.Generic.IEnumerator IParentClass’. An explicit conversion exists (are you missing a cast?) 简
我的构建中出现错误,其中说:

Error 12 Cannot implicitly convert
type
‘System.Collections.Generic.IEnumerator< BaseClass>’
to
‘System.Collections.Generic.IEnumerator< IParentClass>’.
An explicit conversion exists (are you
missing a cast?)

简单地把它扔掉是不对的?

这是我的代码:

public Dictionary<Int32,BaseClass> Map { get; private set; }

public IEnumerator<BaseClass> GetEnumerator()
        {
            return this.Map.Values.GetEnumerator();
        }

public IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator()
        {
            return this.GetEnumerator(); // ERROR!
        }

我的问题是,我可以改变这一行:

return this.GetEnumerator();

至:

return (IEnumerator<IParentClass>)this.GetEnumerator();

(没有任何不良副作用)?

一般承认的答案:
我已将功能更改为以下内容(阅读Jon Skeet的帖子后):

IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator()
        {
            return this.Map.Values.Cast<IParentClass>().GetEnumerator();
        }

解决方法

不,你不能,因为仿制品目前在C#中并不协变. .NET本身有一些支持(对于委托和接口),但它尚未真正使用.

如果你要返回IEnumerable< BaseClass>而不是IEnumerator< BaseClass> (并假设.NEt 3.5)您可以使用Enumerable.Cast – 但您目前需要编写自己的扩展方法,例如

public static IEnumerator<TParent> Upcast<TParent,TChild>
    (this IEnumerator<TChild> source)
    where TChild : TParent
{
    while (source.MoveNext())
    {
        yield return source.Current;
    }
}

或者在您的情况下,您可以使用之前的Cast:

return this.Map.Values.Cast<BaseClass>().GetEnumerator();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读