gpt4 book ai didi

c# - 为什么 "Covariance"和 "Contravariance"的概念在实现接口(interface)的方法时适用?

转载 作者:太空狗 更新时间:2023-10-29 23:50:14 24 4
gpt4 key购买 nike

用例是这样的:

public class SomeClass : ICloneable
{
// Some Code

// Implementing interface method
public object Clone()
{
// Some Clonning Code
}
}

现在我的问题是如果我们考虑 Funda 的协变和逆变,为什么不能使用“SomeClass(因为它是从对象派生的)”作为 Clone() 方法的返回类型

有人可以向我解释一下 Microsoft 的这种实现背后的原因吗????

最佳答案

让我改一下问题:

Languages such as C++ allow an overriding method to have a more specific return type than the overridden method. For example, if we have types

abstract class Enclosure {}
class Aquarium : Enclosure {}
abstract class Animal
{
public virtual Enclosure GetEnclosure();
}

then this is not legal in C# but the equivalent code would be legal in C++:

class Fish : Animal
{
public override Aquarium GetEnclosure() { ...

What is this feature of C++ called?

该功能称为“返回类型协方差”。 (正如另一个答案指出的那样,也可以支持“形式参数类型逆变”,尽管 C++ 不支持。)

Why is it not supported in C#?

正如我多次指出的那样,我们不必提供不支持某项功能的原因;所有功能的默认状态都是“不支持”。只有在投入大量时间和精力进行实现时,功能才会受到支持。相反, 实现的功能必须有它们的理由,并且考虑到制作它们的成本是多么好的理由。

也就是说,此功能有两大“反对点”,是阻止它完成的主要因素。

  1. CLR 不支持它。为了完成这项工作,我们基本上必须实现完全匹配的方法,然后创建一个调用它的辅助方法。这是可行的,但会变得困惑。

  2. Anders 认为这不是一个很好的语言特性。 Anders 是首席架构师,如果他认为这是一个糟糕的功能,那么它很可能不会完成。 (现在,请注意,我们认为命名参数和可选参数也不值得付出代价,但最终还是做到了。有时很明显,您确实必须咬紧牙关实现一个您并不真正喜欢的功能的美学以满足现实世界的需求。)

简而言之,它肯定会有用的时候,这是一个经常被请求的功能。但是,我们不太可能这样做。该功能的好处不支付其成本;它使方法的语义分析变得相当复杂,而且我们没有真正简单的方法来实现它。

关于c# - 为什么 "Covariance"和 "Contravariance"的概念在实现接口(interface)的方法时适用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32939371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com