2013-12-09 168 views
-3

我明白C#接口繼承(可以繼承多少其他接口)

a class can inherit multiple interfaces and 

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

如何回合接口繼承,

一個接口從多個接口繼承?

+1

是的,它可以。來自任何數量。試一試! – Baldrick

+1

是的,你可以。實際上你很快就能做出這些。 – Rex

+2

不是創建幾個類並直接測試它比在SO上詢問更快嗎? –

回答

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)一節中介紹。可悲的是。