C#接口继承(可以继承多少其他接口)

时间:2013-12-09 04:49:21

标签: c# interface

我理解

a class can inherit multiple interfaces and

a abstract class can inherit from another class  and one or more interfaces

bout接口继承如何,

接口可以从多个接口继承吗?

2 个答案:

答案 0 :(得分:2)

是的,它可以。看看ICollection<T>

public interface ICollection<T> : IEnumerable<T>, IEnumerable

答案 1 :(得分:1)

interface 未继承 已实施,因此它不参与“单一继承”规则。任何可以实现interface的东西都可以实现多个接口。

稍微令人困惑的事情 - 以及您的问题的答案 - 是接口可以实现其他接口。实际上,接口继承了它实现的每个接口的所有特性:

interface IHasPosition
{
    float X { get; }
    float Y { get; }
}

interface IHasValue<T>
{
    T Value { get; }
}

interface IPositionValue<T> : IHasPosition, IHasValue<T>
{ }

IPositionValue<T>不是简单的空接口,而是具有它实现的两个接口的所有三个属性。在创建实现IPositionValue<T>的类时,该类会自动实现IPositionValue<T>实现的接口:

class StringAtLocation : IPositionValue<string>
{
    public float X { get; set; }
    public float Y { get; set; }
    public string Value { get; set; }
}

static void Main()
{
    StringAtLocation foo = new StringAtLocation { X = 0, Y = 0, Value = "foo" };
    // All of the following are valid because of interface inheritence:
    IHasPosition ihp = foo;
    IHasValue<string> ihv = foo;
    IPositionValue<string> ipv = foo;       
}

不,它没有记录在interface keyword文档或MSDN上的Interfaces (C# Programming Guide)部分。不幸的是

相关问题