Csharp/CSharp Tutorial/Class/Interface hierarchy

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Inheritance from both class and interface

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...");
        }
    }
}

Interface Inheritance Demo

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();
    }
}

Interfaces Based on Interfaces

  1. One interface can inherit another.
  2. The syntax is the same as for inheriting classes.


using System.Runtime.Serialization;
using System;
interface IComparableSerializable : IComparable, ISerializable
{
    string GetStatusString();
}

Interfaces Inheriting Interfaces

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());
   }
}
5

One interface can inherit another.

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(); 
  } 
}
Implement meth1().
Implement meth2().
Implement meth3().