インターフェースはクラスと同じ方法で継承することができます。
また、継承先のインターフェースで継承元のインターフェースと同じシグニチャを持つメンバを隠蔽することもできます。
継承元と継承先のインターフェース参照変数も利用できます。当然継承元では、継承先の ことはわかりません。
// interface07.cs
using System;
public interface IInterface1
{
void Pulus(int x, int y, out int z);
}
public interface IInterface2 : IInterface1
{
void Minus(int x, int y, out int z);
}
class MyClass : IInterface2
{
public void Pulus(int x, int y, out int z)
{
z = x + y;
}
public void Minus(int x, int y, out int z)
{
z = x - y;
}
}
class interface07
{
public static void Main()
{
MyClass mc = new MyClass();
int ans;
mc.Pulus(3, 5, out ans);
Console.WriteLine("{0} + {1} = {2}", 3, 5, ans);
mc.Minus(3, 5, out ans);
Console.WriteLine("{0} - {1} = {2}", 3, 5, ans);
Console.WriteLine("IInterface1の参照変数を利用");
IInterface1 i1 = mc;
i1.Pulus(3, 5, out ans);
Console.WriteLine("{0} + {1} = {2}", 3, 5, ans);
Console.WriteLine("IInterface2の参照変数を利用");
IInterface2 i2 = mc;
i2.Pulus(3, 5, out ans);
Console.WriteLine("{0} + {1} = {2}", 3, 5, ans);
i2.Minus(3, 5, out ans);
Console.WriteLine("{0} - {1} = {2}", 3, 5, ans);
}
}
IInterface2はIInterface1を継承しています。MyClassクラスはIInterface2を実装しています。結果的に、MyClassは、IInterface1とIInterface2のメンバのすべてを実装しています。MyClassのインスタンスmcは、IInterface1, IInterface2のすべてのメンバを利用できます。IInterface1の参照変数I1にmcを代入した場合、IInterface1のメンバしか利用できません。IInterface2の参照変数I2にmcを代入するとIInterface1, IInterface2の両方のメンバを利用できます。
実行結果は次のようになります。
Update 06/Oct/2006 By Y.Kumei