为什么C#/ CLR不支持方法重写CO /禁忌变化?重写、不支持、禁忌、方法

2023-09-02 01:50:18 作者:浸月.

有相当多的问题和放大器;关于黑客周围的C#不允许方法返回(及参数)类型更改为兼容的类型上覆盖的限制,但答案为什么没有这种限制存在,无论是在C#编译器或CLR?正如我在看,没有什么可以打破,如果CO /禁忌变化是允许的,那么什么是其背后的原因何在呢?

有一个类似的问题可能会被要求扩大接入参数 - 比如覆盖一个受保护的内部方法与公共法(一些东西,Java支持,IIRC)

解决方案

埃里克利珀已经回答了这个办法比我所能。

查看他的系列协变和逆变的C#

基于 CLR 的远程代码 loading 技术以及相应的 SOC 检测方法

How做C#4.0泛型协方差和放大器;魂斗罗方差Implmeneted?

编辑:埃里克指出,他没有谈及返回类型协方差,但我决定继续在这个答案的链接,因为它是一个很酷的系列文章,有人可能会发现它有用的,如果找了这个话题

此功能已要求以及近5年前微软的回答是:谢谢你的记录本。我们听到这个要求很多,我们会考虑它的下一个版本。

而现在我还要举乔恩斯基特,因为它不会在计算器一个合适的回答,而不由乔恩飞碟双向的答案。 协方差和无效的返回类型

  

我强烈怀疑,答案   在于CLR执行   而不是在任何深层语义   原因 - CLR可能需要   知道能不能有将   是一个返回值,以做   与堆栈合适的事情。   即便如此,似乎有点可惜的,在   术语的优雅。我不能说我已经   曾经觉得需要这在现实   生活中,这将是相当容易   假(最多四个参数)的   .NET 3.5只是写一个转换器   从函数功能:其中,X> 动作&其中,X> 函数功能:其中,X,Y>   以动作< X,Y> 等,niggles位   虽然:)

There are quite a few questions & answers about hacking around the limitation of C# not allowing method return (and argument) types to be changed to compatible types on overrides, but why does this limitation exist, either in the C# compiler or in the CLR? As I an see, there is nothing that could break if co/contra-variance was allowed, so what is the reasoning behind it?

A similar question could be asked for widening access parameters - eg overriding a protected internal method with a public method (something which Java supports, IIRC)

解决方案

Eric Lippert already answered this way better than I could.

Check out his series on Covariance and Contravariance in C#

and

How does C# 4.0 Generic Covariance & Contra-variance Implmeneted?

EDIT: Eric pointed out that he doesn't talk about return type convariance but I decided to keep the link in this answer because it is a cool series of articles and someone might find it useful if looking up this topic.

This feature has been requested and almost 5 years ago Microsoft has responded with "Thanks for logging this. We hear this request a lot. We'll consider it for the next release."

And now I'll quote Jon Skeet because it would not be a proper answer on StackOverflow without an answer by Jon Skeet. Covariance and void return types

I strongly suspect that the answer lies in the implementation of the CLR rather than in any deep semantic reason - the CLR probably needs to know whether or not there's going to be a return value, in order to do appropriate things with the stack. Even so, it seems a bit of a pity, in terms of elegance. I can't say I've ever felt the need for this in real life, and it would be reasonably easy to fake (for up to four parameters) in .NET 3.5 just by writing a converter from Func<X> to Action<X>, Func<X,Y> to Action<X,Y> etc. It niggles a bit though :)