Csharp/CSharp Tutorial/Class/interface

Материал из .Net Framework эксперт
Версия от 12:16, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Abstract Interface: how the abstract BaseClass can interface.

using System;
public interface ICompare {
    int GetValue();
    int Compare(ICompare ic);
}
abstract public class BaseClass : ICompare {
    int nValue;
    public BaseClass(int nInitialValue) {
        nValue = nInitialValue;
    }
    public int Value {
        get { return GetValue(); }
    }
    public int GetValue() {
        return nValue;
    }
    abstract public int Compare(ICompare bc);
}
public class SubClass : BaseClass {
    public SubClass(int nInitialValue)
        : base(nInitialValue) {
    }
    override public int Compare(ICompare ic) {
        return GetValue().rupareTo(ic.GetValue());
    }
}
public class Class1 {
    public static void Main(string[] strings) {
        SubClass sc1 = new SubClass(10);
        SubClass sc2 = new SubClass(20);
        MyFunc(sc1, sc2);
    }
    public static void MyFunc(ICompare ic1, ICompare ic2) {
        Console.WriteLine("bc1.rupare(bc2) returned {0}",
                          ic1.rupare(ic2));
    }
}

Accessing an interface from a class.

using System;
public interface Channel {
    void Next();
    void Previous();
}
public interface Book {
    void Next();
    void Chapter();
}
public class MainClass : Channel, Book {
    void Channel.Next() {
        Console.WriteLine("Channel Next");
    }
    void Book.Next() {
        Console.WriteLine("Book Next");
    }
    public void Previous() {
        Console.WriteLine("Previous");
    }
    public void Chapter() {
        Console.WriteLine("Chapter");
    }
    public static void Main() {
        MainClass app = new MainClass();
        ((Book)app).Next();
        app.Previous();
        app.Chapter();
    }
}

Base class and interface

public class Component
{
    public Component() {}
}
interface Printable
{
    void printHeader(float factor);
    void printFooter(float factor);
}
public class TextField: Component, Printable
{
    public TextField(string text)
    {
        this.text = text;
    }
    // implementing Printable.printHeader()
    public void printHeader(float factor)
    {
        
    }
    
    // implementing Printable.printFooter()
    public void printFooter(float factor)
    {
        
    }
    
    private string text;
}
class MainClass
{
    public static void Main()
    {
        TextField text = new TextField("Hello");
        
        Printable scalable = (Printable) text;
        scalable.printHeader(0.5F);
        scalable.printFooter(0.5F);
    }
}

Creating an interface.

using System;
public interface ILog {
    int OpenLogFile(string fileName);
    int CloseLogFile();
    void LogString(string strToLog);
}
public class MyLog : ILog {
    public int OpenLogFile(string fileName) {
        Console.WriteLine("Opening File {0}", fileName);
        return 0;
    }
    public int CloseLogFile() {
        Console.WriteLine("Closing log file");
        return 0;
    }
    public void LogString(string strToLog) {
        Console.WriteLine("Logging String {0}", strToLog);
    }
}
class MainClass {
    public static void Main() {
        MyLog app = new MyLog();
        app.OpenLogFile("AFile");
        app.LogString("Hello world");
        app.CloseLogFile();
    }
}

Declare an interface and implement it

interface IMyIF { 
  int myMeth(int x); 
}
class MyClass : IMyIF { 
  int IMyIF.myMeth(int x) { 
    return x / 3; 
  } 
}

Duplicate Interface Members

using System;
interface Interface1
{
   void PrintOut(string s);
}
interface Interface2
{
   void PrintOut(string t);
}
class MyClass : Interface1, Interface2         
{
   public void PrintOut(string s)    
   {
      Console.WriteLine("Calling through: {0}", s);
   }
}
class MainClass
{
   static void Main()
   {
      MyClass mc = new MyClass();
      mc.PrintOut("object.");
   }
}
Calling through: object.

Implement an interface

The general form of a class that implements an interface is shown here:


class class-name : interface-name {
// class-body
}

Inherited interface

using System;
public interface ISeries { 
  int getNext(); 
  void setStart(int x); 
}

class Sequence : ISeries { 
  int val; 
 
  public Sequence() { 
  }  
 
  public int getNext() { 
    return val++; 
  } 
 
  public void setStart(int x) { 
    val = x; 
  } 
}
 
class MainClass { 
  public static void Main() { 
    Sequence ob = new Sequence(); 
 
    for(int i=0; i < 5; i++) 
      Console.WriteLine("Next value is " + ob.getNext()); 
 
 
    Console.WriteLine("\nStarting at 100"); 
    ob.setStart(100); 
    for(int i=0; i < 5; i++) 
      Console.WriteLine("Next value is " + ob.getNext()); 
  } 
}
Next value is 0
Next value is 1
Next value is 2
Next value is 3
Next value is 4
Starting at 100
Next value is 100
Next value is 101
Next value is 102
Next value is 103
Next value is 104

Interface Explicit Implementation

using System;

    interface IStorable
    {
        void Read();
        void Write();
    }
    interface ITalk
    {
        void Talk();
        void Read();
    }
    public class Document : IStorable, ITalk
    {
         public Document(string s)
        {
            Console.WriteLine("Creating document with: {0}", s);
        }
        public virtual void Read()
        {
            Console.WriteLine("Implementing IStorable.Read");
        }
        public void Write()
        {
            Console.WriteLine("Implementing IStorable.Write");
        }
        void ITalk.Read()
        {
            Console.WriteLine("Implementing ITalk.Read");
        }
        public void Talk()
        {
            Console.WriteLine("Implementing ITalk.Talk");
        }
    }
    public class Tester
    {
        static void Main()
        {
            Document theDoc = new Document("Test Document");
            IStorable isDoc = theDoc;
            isDoc.Read();
            ITalk itDoc = theDoc;
            itDoc.Read();
            theDoc.Read();
            theDoc.Talk();
        }
    }

Interface Properties

Here is the general form of a property specification:


// interface property
type name {
    get;
    set;
}

Interfaces

  1. An interface provides no implementation.
  2. Interfaces are declared by using the interface keyword.

Here is a simplified form of an interface declaration:


interface name {
        ret-type method-name1(param-list);
        ret-type method-name2(param-list);
        // ...
        ret-type method-nameN(param-list);
    }

Interfaces and Inheritance

using System;
interface MyInterface
{
    void MyMethodInInterface();
}
public class Base: MyInterface
{
    public void MyMethodInInterface()
    {
        Console.WriteLine("Base.MyMethodInInterface()");
    }
}
public class Derived: Base
{
    public new void MyMethodInInterface()
    {
        Console.WriteLine("Derived.MyMethodInInterface()");
    }
}
class MainClass
{
    public static void Main()
    {
        Derived der = new Derived();
        der.MyMethodInInterface();
        MyInterface helper = (MyInterface) der;
        helper.MyMethodInInterface();
    }
}
Derived.MyMethodInInterface()
Base.MyMethodInInterface()

Multiple Implementation: implement two interfaces

interface IFoo
{
    void ExecuteFoo();
}
interface IBar
{
    void ExecuteBar();
}
class Tester: IFoo, IBar
{
    public void ExecuteFoo() {}
    public void ExecuteBar() {}
}

Multiple Interfaces

using System;
    interface IVolumeControl
    {
        int Current
        {
            get;
        }
    }
  
    interface ISpeedControl
    {
        int Current
        {
            get;
        }
    }
    public class Radio : IVolumeControl, ISpeedControl
    {
        int IVolumeControl.Current
        {
            get
            {
                return 1;
            }
        }
        int ISpeedControl.Current
        {
            get
            {
                return 2;
            }
        }
    }
    class Class1
    { 
        [STAThread]
        static void Main(string[] args)
        {
           ISpeedControl radioDial = (ISpeedControl) new Radio();
           Console.WriteLine( "Current Speed = {0}", radioDial.Current );
        }
    }

Use interface keyword to define an interface

using System;
interface Interface1
{
   void PrintOut(string s);
}
class MyClass : Interface1
{
   public void PrintOut(string s)
   {
      Console.WriteLine("Calling through: {0}", s);
   }
}
class MainClass
{
   static void Main()
   {
      MyClass mc = new MyClass();
      mc.PrintOut("object.");
   }
}
Calling through: object.