2010-10-26 225 views
2

我有一個我們如何能夠實現具有這樣我們如何實現具有相同方法名稱的兩個接口?

interface ISample2 
{ 
    string CurrentTime(); 
    string CurrentTime(string name); 
} 
interface ISample1 
{ 
    string CurrentTime(); 
} 

我不喜歡這樣。就是這種權利相同的方法名界面的問題嗎?

class TwoInterfacesHavingSameMethodName:ISample1,ISample2 
{ 
    static void Main(string[] sai) 
    { 
     ISample1 obj1 = new TwoInterfacesHavingSameMethodName(); 
     Console.Write(obj1.CurrentTime()); 
     ISample2 obj2 = new TwoInterfacesHavingSameMethodName(); 
     Console.Write(obj2.CurrentTime("SAI")); 
     Console.ReadKey(); 
    } 

    #region ISample1 Members 

    string ISample1.CurrentTime() 
    { 
     return "Interface1:" + DateTime.Now.ToString(); 
    } 

    #endregion 

    #region ISample2 Members 

    string ISample2.CurrentTime() 
    { 
     return "Interface2:FirstMethod" + DateTime.Now.ToString(); 
    } 

    string ISample2.CurrentTime(string name) 
    { 
     return "Interface2:SecondMethod" + DateTime.Now.ToString() + "" + name; 
    } 

    #endregion 
} 

這裏是什麼這行的含義:

ISample1 obj1 = new TwoInterfacesHavingSameMethodName(); 

是我們創建類或Interface.What是基本採用書面形式在接口中的方法的對象。

回答

5

當您明確實現一個接口時,僅當您從對該接口的引用調用顯式實現時纔會調用顯式實現。

所以如果你會寫:

TwoInterfacesHavingSameMethodName obj1 = new TwoInterfacesHavingSameMethodName(); 
    obj1.CurrentTime(); 

,你會得到一個錯誤。

ISample1 obj1 = new TwoInterfacesHavingSameMethodName(); 
ISample2 obj2 = new TwoInterfacesHavingSameMethodName(); 
obj1.CurrentTime(); 
obj2.CurrentTime(); 

會工作。

如果你想在TwoInterfacesHavingSameMethodName上調用這個函數,你也必須隱式地實現這個接口。例如:

public string CurrentTime() 
{ 
    return "Implicit"; 
} 
0

是的,你所做的是正確的。 要回答你的第二個問題,你總是創建一個類的對象和類型的接口。 在接口中使用寫入方法是強制所有類實現該方法。

相關問題