如何在C#中调用特定的显式声明的接口方法

时间:2013-02-25 20:46:45

标签: c# .net interface

我对如何在以下代码中调用特定接口的方法(Say IA或IB或In ...)有疑问。请帮我解决如何打电话。我已经注释了代码行,我声明接口方法“public”,在这种情况下它可以工作。当我明确宣布时,我不知道如何调用它:(我正在学习C#....

interface IA
    {
        void Display();
    }
    interface IB
    {
        void Display();
    }
    class Model : IA, IB
    {
        void IA.Display()
        {
            Console.WriteLine("I am from A");
        }
        void IB.Display()
        {
            Console.WriteLine("I am from B");
        }
        //public void Display()
        //{
        //    Console.WriteLine("I am from the class method");
        //}

        static void Main()
        {
            Model m = new Model();
            //m.Display();
            Console.ReadLine();
        }
    }

4 个答案:

答案 0 :(得分:12)

要调用显式接口方法,您需要使用正确类型的变量,或直接转换为该接口:

    static void Main()
    {
        Model m = new Model();

        // Set to IA
        IA asIA = m;
        asIA.Display();

        // Or use cast inline
        ((IB)m).Display();

        Console.ReadLine();
    }

答案 1 :(得分:3)

将调用的方法取决于调用它的类型。例如:

注意,为了清楚起见,我创建了两个项目。但实际上,你不想这样做,你应该只在类型之间转换对象。

static void Main(string[] args)
{
    // easy to understand version:
    IA a = new Model();
    IB b = new Model();

    a.Display();
    b.Display();

    // better practice version:
    Model model = new Model();

    (IA)model.Display();
    (IB)model.Display();
}

interface IA
{
    void Display();
}

interface IB
{
    void Display();
}

class Model : IA, IB
{
    void IA.Display()
    {
        Debug.WriteLine("I am from A");
    }

    void IB.Display()
    {
        Debug.WriteLine("I am from B");
    }            
}

输出:

I am from A
I am from B

答案 2 :(得分:2)

您需要在此过程中使用 explicit interface implementation

  

如果两个接口成员不执行相同的功能,   但是,这可能导致一个或两个的错误实现   的接口。可以实现接口成员   显式创建一个只通过该方法调用的类成员   接口,并且特定于该接口。这是通过   使用接口名称和句点命名类成员。

interface IA
{
   void Display();
}
interface IB
{
   void Display();
}

    public class Program:IA,IB
    {

        void IA.Display()
        {
            Console.WriteLine("I am from A");
        }

        void IB.Display()
        {
            Console.WriteLine("I am from B");
        }

        public static void Main(string[] args)
        {
           IA p1 = new Program();
           p1.Display();
           IB p2 = new Program();
           p2.Display();
        }
    }

输出将是:

I am from A
I am from B

这是 DEMO

答案 3 :(得分:2)

为了调用显式接口方法,您必须持有对该接口类型的引用或者对其进行强制转换:

IB ib = new Model();
ib.Display();

IA ia = (IA)ib;
ia.Display();