2012-01-12 47 views
0

(面试问题) 你能给我一个在类中实现的接口的例子,你可以在其中调用它的隐式方法,但不是明确的方法吗?可以调用接口隐式方法,但不能调用显式方法吗? (面试任务!)

+0

你的意思是你不能调用显式重写接口方法的类吗? – rerun 2012-01-12 16:08:16

+0

你是什么意思的类中的隐式和显式方法实现了接口?你的意思是访问修饰符像公共和私人? – Mharlin 2012-01-12 16:09:19

+0

@rerun正确。 – Idrees 2012-01-12 16:25:42

回答

0

实施例:

组件1:

internal interface IFlyable 
{ 
    void Fly(); 
} 

public class Bird: IFlyable 
{ 
    public void Fly() { ... } 
    void IFlyable.Fly() { ... } 
} 

组件2:

Bird bird = new Bird(); 
bird.Fly(); 
((IFlyable)bird).Fly() // Error, IFlyable is internal 

这是一个面试问题。聪明的一个,如果你考虑一下。

2
interface IA 
{ 
    void Method1(); 
    void Method2(); 
    void Method3(); 
} 

class A : IA 
{ 
    // Implicit implementation 
    public void Method1() 
    { 
    } 

    // Explicit implementation 
    void IA.Method2() 
    { 
    } 

    // Implicit + explicit implementation! 
    public void Method3() 
    { 
    } 

    void IA.Method3() 
    { 
    } 
} 

class TestImplicitExplicit 
{ 
    public void Test() 
    { 
     A a = new A(); 
     a.Method1(); // ok 
     //a.Method2(); // does not compile 
     a.Method3(); // ok 

     IA ia = a; 
     ia.Method1(); // ok 
     ia.Method2(); // ok 
     ia.Method3(); // ok (calls another method than a.Method3(); !) 
    } 
} 

显式实现只能通过接口看到。

+0

当您声明ia或类型IA时,仍然可以调用Method2。所以这是可行的?你能想到一个你不能这样做的情况吗? – Idrees 2012-01-12 16:45:49

+0

它应该始终工作。奇怪的是,你甚至可以同时显式和隐式地实现相同的方法! – 2012-01-12 16:55:39

+0

并不总是... – Idrees 2012-01-12 17:09:22

相关问题