一個接口得到不同的實現:
using System;
interface MyInterface
{
int Method(int x, int y);
}
class MyClass1 : MyInterface
{
public int Method(int x, int y) { return x + y; }
}
class MyClass2 : MyInterface
{
public int Method(int x, int y) { return x - y; }
}
class Program
{
static void Main()
{
MyInterface intf1 = new MyClass1();
MyInterface intf2 = new MyClass2();
Console.WriteLine(intf1.Method(3, 2)); // 5
Console.WriteLine(intf2.Method(3, 2)); // 1
Console.ReadKey();
}
}
顯示實現接口(接口名.方法):
using System;
interface MyInterface1
{
void Method();
}
interface MyInterface2
{
void Method();
}
class MyClass : MyInterface1, MyInterface2
{
/* 顯示實現接口不需要訪問修飾符; 但顯示實現的方法只能通過接口訪問 */
void MyInterface1.Method() { Console.WriteLine("MyInterface1_Method"); }
void MyInterface2.Method() { Console.WriteLine("MyInterface2_Method"); }
}
class Program
{
static void Main()
{
MyInterface1 intf1 = new MyClass();
MyInterface2 intf2 = new MyClass();
intf1.Method(); // MyInterface1_Method
intf2.Method(); // MyInterface2_Method
Console.ReadKey();
}
}