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

标签 c# methods covariance vtable

有什么方法可以将协变覆盖“破解”或“强制”到 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”中,它只是基本上声明了一个具有相同名称的全新方法,因此意味着通过指向的指针访问 Beta Alpha 将调用 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();
    }
}

关于c# - 覆盖虚拟方法时缺少返回类型协变的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25817771/

相关文章:

c# - 在 Android 上的 Unity 中从 C++ DLL 访问 StreamingAssets 资源

c# - UPDATE 语句 SQL 更新 MS Access 数据库 C# 中的语法错误

c# - CookieContainer : The 'Path' part of the cookie is invalid 的 CookieException

java - 如何将多个按键事件传递到一个方法中?

swift - 可选协方差如何在 Swift 中工作

c# - 分页错误 :The method 'Skip' is only supported for sorted input in LINQ to Entities. 方法 'OrderBy' 必须在方法 'Skip' 之前调用

ruby - 我可以告诉 Ruby 方法期望特定的参数类型吗?

c++ - 在不触及字段本身的情况下修改/允许修改引用值的方法使用或不使用 const

c# - IObservable .Cast<>() 和协方差

generics - 在 Go 中实现通用映射器的惯用方法