gpt4 book ai didi

c# - 接口(interface)实现中成员的返回类型必须与接口(interface)定义完全匹配?

转载 作者:太空狗 更新时间:2023-10-29 17:29:48 26 4
gpt4 key购买 nike

根据 CSharp 语言规范。

An interface defines a contract that can be implemented by classes and structs. An interface does not provide implementations of the members it defines—it merely specifies the members that must be supplied by classes or structs that implement the interface.

所以我有这个:

interface ITest
{
IEnumerable<int> Integers { get; set; }
}

我的意思是。 “我与一个属性的契约(Contract)作为您可以枚举的整数集合”。

然后我想要下面的接口(interface)实现:

class Test : ITest
{
public List<int> Integers { get; set; }
}

我得到以下编译器错误:

'Test' does not implement interface member 'ITest.Integers'. 'Test.Integers' cannot implement 'ITest.Integers' because it does not have the matching return type of 'System.Collections.Generic.IEnumerable'.

只要我可以说我的测试类实现了 ITest 契约,因为 List of int 属性实际上是一个 IEnumerable of int。

那么 C# 编译器是如何告诉我错误的?

最佳答案

仅供引用,您想要的功能称为“虚拟方法返回类型协变”,正如您所发现的,C# 不支持它。它是其他面向对象语言(如 C++)的一个特性。

虽然我们经常收到对此功能的请求,但我们没有计划将其添加到该语言中。这不是一个可怕的功能;如果我们有它,我会使用它。但我们有很多理由不去做,包括它不受 CLR 支持,它为版本化组件添加了新的有趣的故障模式,Anders 认为这不是一个非常有趣的特性,我们有很多很多更高的优先级和有限的预算。

顺便说一句,尽管人们一直要求我们提供虚方法返回类型协变,但从来没有人要求虚方法形式参数类型逆变,即使从逻辑上讲它们本质上是相同的功能。也就是说,我有一个采用长颈鹿的虚方法/接口(interface)方法 M,我想用采用动物的方法 M 覆盖它/实现它。

关于c# - 接口(interface)实现中成员的返回类型必须与接口(interface)定义完全匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7996127/

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