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

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

问题描述

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

只要我可以说我的测试类实现ITEST合同,因为int属性的列表实际上是INT的IEnumerable

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>();

由于测试表示,它包含这对无效测试合约列表与LT; INT方式&gt;

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

现在,您可以使用显式接口实现,使其能够满足这取决于它是从一个 ITEST 引用或叫这两个标记测试引用:

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

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

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