2013-12-13 50 views
2

我一直在試圖理解實際是什麼接口,理論上我已經很好地解釋了這個定義。但是在實際使用它們時,我會想到一些問題。接口的使用,實際的和真實世界的例子

大多數資源定義界面是這樣的:

「An interface is a contract between itself and any class that implements it. This contract states that any class that implements the interface will implement the interface's properties, methods and/or events. An interface contains no implementation, only the signatures of the functionality the interface provides. An interface can contain signatures of methods, properties, indexers & events.」

這是很容易理解的,但我的問題是,如果接口(根據這個定義)某種它們之間的藍圖或合同和類,如果我定義這個接口實際上會發生什麼,

interface ITest { 
    int SomeTestVariable { set; get;} 
    int SomeTestMethod();  
} 

使實現此接口的類以及所有它的方法

class Test: ITest { 
    int SomeTestvariable { set; get;} 
    int SomeTestMethod() { 
     return 1; 
    } 
} 

,所有的方法和屬性已經實現,那麼之後我將其刪除。

class Test { 
    int SomeTestvariable { set; get;} 
    int SomeTestMethod() { 
     return 1; 
    } 
} 

現在我必須有一個班級使用這個藍圖或合同。那麼在一張紙上寫這張藍圖並製作界面會有什麼不同?

+0

想想如果你有一個簽名'公共布爾RunTest(ITest測試)' –

+0

@AntP的方法會發生什麼,你是非常正確的,實際上這是我的問題,在什麼情況下我需要有這樣的方法。如果您提供示例,我將不勝感激。 – Transcendent

+0

一個接口允許你強制執行許多不同的具體對象,所有這些對象都具有相同的實現。所以當你食用它們時,你可以確保它們的一致性,並且它們可以來自許多不同的地方..現在@Servy的答案將勝過我的; D – paqogomez

回答

8

好處是你可以編寫接口,並在任何人寫過它的實現之前編寫使用接口的代碼

當然,如果您已經擁有唯一一個在您使用該接口之前實現接口編碼的類,那麼該接口並沒有好處,但是如果您還沒有編寫實現方案(還要考慮這種情況有多種類型正在實現接口)?

一個簡單的例子是編寫一個簡單的方法Sort。我可以爲每種可能的數據類型編寫一個Sort實現,或者我可以編寫一種排序方法,假定每個項目實現IComparable接口並可以比較自己。然後,我的Sort方法可以在您編寫要比較的對象很久之前使用該接口編寫代碼。

+0

你的答案帶來了泛型,我想現在我有一些想法接口的優點:)我會接受你的回答 – Transcendent

+0

@Servy但不是IComparable接口它不會包含實現,所以每一個繼承自IComparable的類型都將定義它自己的比較實現? –

+0

@EhsanSajjad是的,這是正確的。 – Servy

5

Servy的回答是一個堅實的解釋,但 - 你自找的例子 - 我願意回答大家的接口,並將其延伸到一個可能的(如果稍有做作)的情況。

假設您的接口ITest已到位(我偷偷地切換SomeTestMethod以在我的示例中返回bool)。我現在可以有兩個不同的類:

// Determines whether an int is greater than zero 
public class GreaterThanZeroTest : ITest 
{ 
    public int SomeTestVariable { get; set; } 

    public bool SomeTestMethod() 
    { 
     return SomeTestVariable > 0; 
    } 
} 

// Determines whether an int is less than zero 
public class LessThanZeroTest : ITest 
{ 
    public int SomeTestVariable { get; set; } 

    public bool SomeTestMethod() 
    { 
     return SomeTestVariable < 0; 
    } 
} 

現在讓我們說,我們有一個單獨的類運行測試。我們可以有以下方法:

public bool RunTest(ITest test) 
{ 
    return test.SomeTestMethod(); 
} 

也許這種方法是通過此類設計的運行分批測試的其他成員要求,生產統計等

現在,您可以創建各種「試驗「班。這些可以是任意複雜的,但是 - 只要它們實現了ITest - 您將始終能夠將它們傳遞給您的測試執行器。

+0

非常好的例子螞蟻P,非常感謝你 – Transcendent