2015-06-16 31 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"); 
    } 
}