接口实现上成员的返回类型必须与接口定义完全匹配吗? [英] The return type of the members on an Interface Implementation must match exactly the interface definition?

查看:101
本文介绍了接口实现上成员的返回类型必须与接口定义完全匹配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据CSharp语言规范。

According to CSharp Language Specification.


接口定义了可以由类和
结构实现的合同。接口不提供其定义的成员
的实现,仅指定必须由实现该接口的
类或结构提供的成员。

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; }
}

我的意思是。 我有一个带有属性的合同,可以将其枚举为整数。

And what I mean is. "I have a contract with a property as a collection of integers that you can enumerate".

然后,我需要以下接口实现:

Then I want the following interface Implementation:

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

我得到以下编译器错误:

And I get the following compiler error:


测试未实现接口成员 ITest.Integers。
'Test.Integers'无法实现'ITest.Integers',因为它没有
具有匹配的返回类型
'System.Collections.Generic.IEnumerable'。

'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'.

只要我可以说我的Test类实现了ITest合同,因为int属性的列表实际上是一个IEnumerable int。

As long as I can say my Test class implement the ITest contract because the List of int property is in fact an IEnumerable of int.

这样C#编译器告诉我有关错误的信息吗?

So way the c# compiler is telling me about the error?

推荐答案

这样做是因为如果允许的话,根据实现的不同,您手头上会有一个大问题。考虑:

You can't do this because you'd have a major problem on your hand depending on the implementation if this were allowed. Consider:

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

class Test : ITest
{
    // if this were allowed....
    public List<int> Integers { get; set; }
}

这将允许:

ITest test = new Test();
test.Integers = new HashSet<int>();

这将使Test的合同无效,因为Test表示其中包含 List< int> ;

This would invalidate the contract for Test because Test says it contains List<int>.

现在,您可以使用显式接口实现,使其根据两个签名是否满足两个签名从 ITest 引用或 Test 引用调用:

Now, you can use explicit interface implementation to allow it to satisfy both signatures depending on whether it's called from an ITest reference or a Test reference:

class Test : ITest
{
    // satisfies interface explicitly when called from ITest reference
    IEnumerable<int> ITest.Integers
    {
        get
        {
            return this.Integers; 
        }
        set
        {
            this.Integers = new List<int>(value);
        }
    }

    // allows you to go directly to List<int> when used from reference of type Test
    public List<int> Integers { get; set; }
}

这篇关于接口实现上成员的返回类型必须与接口定义完全匹配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆