2015-06-16 35 views
0

C#支持區分具有相同名稱的方法的內置機制。下面是一個簡單的例子,顯示它如何工作:C#中顯式接口實現的優點是什麼?

interface IVehicle{ 
    //identify vehicle by model, make, year 
    void IdentifySelf();  
} 

interface IRobot{ 
    //identify robot by name 
    void IdentifySelf(); 
} 

class TransformingRobot : IRobot, IVehicle{ 
    void IRobot.IdentifySelf(){ 
     Console.WriteLine("Robot"); 
    } 

    void IVehicle.IdentifySelf(){ 
     Console.WriteLine("Vehicle"); 
    } 
} 

這種區別的用例或好處是什麼?我真的需要區分實現類的抽象方法嗎?

回答

1

在你的情況下,沒有真正的好處,事實上有兩種方法只是讓用戶感到困惑。然而,它們是關鍵時,你有:

interface IVehicle 
{ 
    CarDetails IdentifySelf();  
} 

interface IRobot 
{ 
    string IdentifySelf(); 
} 

現在我們有兩個同名的方法,但不同的返回類型。所以它們不能超載(返回類型被忽略超載),但它們可以被明確引用:

class TransformingRobot : IRobot, IVehicle 
{ 
    string IRobot.IdentifySelf() 
    { 
     return "Robot"; 
    } 

    CarDetails IVehicle.IdentifySelf() 
    { 
     return new CarDetails("Vehicle"); 
    } 
}