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

c# – 覆盖虚拟方法时缺少返回类型协方差的解决方法

发布时间:2020-12-15 08:01:58 所属栏目:百科 来源:网络整理
导读:有什么方法可以“破解”或“胁迫”协变覆盖C#? 例如: public class Alpha { public virtual Alpha DoSomething() { return AlphaFactory.GetAlphaFromSomewhere(); }}public class Beta : Alpha { public override Beta DoSomething() { return BetaFactor
有什么方法可以“破解”或“胁迫”协变覆盖C#?

例如:

public class Alpha {
    public virtual Alpha DoSomething() {
        return AlphaFactory.GetAlphaFromSomewhere();
    }
}
public class Beta : Alpha {
    public override Beta DoSomething() {
        return BetaFactory.GetBetaFromSomewhere();
    }
}

不幸的是,C#不支持这个(这看起来有点荒谬,但这既不在这里也不在那里).

我以为我可能会有方法隐藏的答案:

new public Beta DoSomething() {
    return BetaFactory.GetBetaFromSomewhere();
}

但这并没有将条目添加到’vtable’中,它只是基本上声明了一个具有相同名称的全新方法,因此意味着通过指向Alpha的指针访问Betas将调用Alpha.DoSomething().

那么,有什么好的伎俩吗?

解决方法

你可以用泛型做一些漂亮的东西.
public class Alpha<T> where T: Alpha<T> {
    public virtual T DoSomething() {
        throw new NotImplementedException();
    }
}
public class Beta : Alpha<Beta> {
    public override Beta DoSomething() {
        throw new NotImplementedException();
    }
}

(编辑:李大同)

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

    推荐文章
      热点阅读