微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

public class Thing : IThing
{
    public int[] Collection { get; set; }
}

注意

public class Thing : IThing
{
    public int[] Array { get; set; }
    public IEnumerable<int> Collection
    {
         get
         {
              return this.Array;
         }
    }
}

很好.

解决方法

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

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

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

public class Thing : IThing
{
    public int[] Collection { get; set; }
    IEnumerable<int> IThing.Collection { get { return this.Collection; } }
}

这允许类的公共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();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐