Csharp/CSharp Tutorial/Class/Interface hierarchy
Содержание
Inheritance from both class and interface
<source lang="csharp">using System; public class Control {
public void Serialize() { Console.WriteLine("Control.Serialize called"); }
} public interface IDataBound {
void Serialize();
} public class EditBox : Control, IDataBound { } class InterfaceInh2App {
public static void Main() { EditBox edit = new EditBox(); IDataBound bound = edit as IDataBound; if (bound != null) { Console.WriteLine("IDataBound is supported..."); bound.Serialize(); } else { Console.WriteLine("IDataBound is NOT supported..."); } }
}</source>
Interface Inheritance Demo
<source lang="csharp">using System; interface ITest {
void Foo();
} class Base : ITest {
public void Foo() { Console.WriteLine("Base.Foo (ITest implementation)"); }
} class MyDerived : Base {
public new void Foo() { Console.WriteLine("MyDerived.Foo"); }
} public class InterfaceInh3App {
public static void Main() { MyDerived myDerived = new MyDerived(); Console.WriteLine(); myDerived.Foo(); Console.WriteLine(); ((ITest)myDerived).Foo(); }
}</source>
Interfaces Based on Interfaces
- One interface can inherit another.
- The syntax is the same as for inheriting classes.
<source lang="csharp">using System.Runtime.Serialization;
using System;
interface IComparableSerializable : IComparable, ISerializable
{
string GetStatusString();
}</source>
Interfaces Inheriting Interfaces
<source lang="csharp">using System; interface Getter {
int GetData();
} interface Setter {
void SetData(int x);
} interface GetterAndSetter : Getter, Setter { } class MyData : GetterAndSetter {
int data; public int GetData() { return data; } public void SetData(int x) { data = x; }
} class MainClass {
static void Main() { MyData data = new MyData(); data.SetData(5); Console.WriteLine("{0}", data.GetData()); }
}</source>
5
One interface can inherit another.
<source lang="csharp">using System;
public interface BaseInterface {
void meth1(); void meth2();
}
// BaseInterface now includes meth1() and meth2() -- it adds meth3(). public interface BaseInterface2 : BaseInterface {
void meth3();
}
// This class must implement all of BaseInterface and BaseInterface class MyClass : BaseInterface2 {
public void meth1() { Console.WriteLine("Implement meth1()."); } public void meth2() { Console.WriteLine("Implement meth2()."); } public void meth3() { Console.WriteLine("Implement meth3()."); }
}
class MainClass {
public static void Main() { MyClass ob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); }
}</source>
Implement meth1(). Implement meth2(). Implement meth3().