c#接口实现 - 为什么这不构建?

wax*_*cal 3 c# arrays ienumerable implementation interface

很抱歉,如果之前已经询问过,但谷歌几乎不可能.我认为int数组实现IEnumerable,因此Thing应该能够实现IThing.怎么没有?

public interface IThing
{
    IEnumerable<int> Collection { get; }
}

public class Thing : IThing
{
    public int[] Collection { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

注意

public class Thing : IThing
{
    public int[] Array { get; set; }
    public IEnumerable<int> Collection
    {
         get
         {
              return this.Array;
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

很好.

Ric*_*lly 7

对于要实现的接口,方法签名和返回类型必须相同,因此int []可转换为IEnumerable这一事实对我来说没什么区别.


Ode*_*ded 6

不同实现中属性的返回类型是不同的 - 返回a int[]与返回a不同IEnumerable<int>.

就实现接口而言 - 类型必须完全匹配.

这应该工作得很好:

public class Thing : IThing
{
    public IEnumerable<int> Collection { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


Ree*_*sey 6

接口实现必须完全实现接口.这可以防止您返回实现该接口的类型作为成员.

如果您希望这样做,一个选项是明确实现接口:

public interface IThing
{
    IEnumerable<int> Collection { get; }
}

public class Thing : IThing
{
    public int[] Collection { get; set; }
    IEnumerable<int> IThing.Collection { get { return this.Collection; } }
}
Run Code Online (Sandbox Code Playgroud)

这允许类的公共API使用具体类型,但接口实现要正确实现.

例如,通过上面的内容,您可以编写:

internal class Test
{
    private static void Main(string[] args)
    {
        IThing thing = new Thing { Collection = new[] { 3, 4, 5 } };

        foreach (var i in thing.Collection)
        {
            Console.WriteLine(i);
        }
        Console.ReadKey();
    }
}
Run Code Online (Sandbox Code Playgroud)