将实施哪个界面?

Vij*_*dra 2 c# inheritance interface

我有关于Interface的问题.有2个接口都包含相同的Method Test().现在我继承了Sample类中的接口.我想知道将调用哪个接口的方法?我的代码示例如下:

interface IA 
{
    void Test();
}
interface IB
{
    void Test();
}
class Sample: IA, IB
{
    public void Test()
    {
      Console.WriteLine("Which interface will be implemented IA or IB???!");
    }
}
class Program
{
    public static void Main(string[] args)
    {
        Sample t = new Sample();
        t.Test();//Which Interface's Method will called.
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢Vijendra Singh

Fem*_*ref 12

两者的结果都是一样的.如果您希望每个接口具有不同的行为,则必须明确实现它们:

interface IA 
{
    void Test();
}
interface IB
{
    void Test();
}
class Sample: IA, IB
{
    void IA.Test()
    {
      Console.WriteLine("Hi from IA");
    }
    void IB.Test()
    {
      Console.WriteLine("Hi from IB");
    }
    public void Test() //default implementation
    {
      Console.WriteLine("Hi from Sample");
    }
}

class Program
{
    public static void Main(string[] args)
    {
        Sample t = new Sample();
        t.Test(); // "Hi from Sample"
        ((IA)t).Test(); // "Hi from IA"
        ((IB)t).Test(); // "Hi from IB"
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要默认行为,请创建具有相同签名的方法(因此是隐式接口实现)并为该案例添加代码.通常,您只需要显式实现.


fam*_*iro 9

都.

如果你有代码

IA a = new Sample();
Run Code Online (Sandbox Code Playgroud)

要么

IB b = new Sample();
Run Code Online (Sandbox Code Playgroud)

输出是一样的.

编辑

叫什么界面?

两者都实现调用.

存在接口以使程序员了解该类的方法(什么接口).

您需要使用接口的具体实现.具体类的方法是被调用的方法.

  • 接口无法调用,它不包含实现. (4认同)