Csharp/C Sharp/Class Interface/Interface — различия между версиями

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

Версия 15:31, 26 мая 2010

Add an indexer in an interface

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Add an indexer in an interface. 
 
using System; 
 
public interface ISeries { 
  // an interface property 
  int next { 
    get; // return the next number in series 
    set; // set next number 
  } 
 
  // an interface indexer 
  int this[int index] { 
    get; // return the specified number in series 
  } 
} 
 
// Implement ISeries. 
class ByTwos : ISeries { 
  int val; 
 
  public ByTwos() { 
    val = 0; 
  }  
 
  // get or set value using a property 
  public int next { 
    get {  
      val += 2; 
      return val; 
    } 
    set { 
      val = value; 
    } 
  } 
 
  // get a value using an index 
  public int this[int index] { 
    get {  
      val = 0; 
      for(int i=0; i<index; i++) 
        val += 2; 
      return val; 
    } 
  } 
} 
 
// Demonstrate an interface indexer. 
public class SeriesDemo4 { 
  public static void Main() { 
    ByTwos ob = new ByTwos(); 
 
    // access series through a property 
    for(int i=0; i < 5; i++) 
      Console.WriteLine("Next value is " + ob.next); 
 
    Console.WriteLine("\nStarting at 21"); 
    ob.next = 21; 
    for(int i=0; i < 5; i++) 
      Console.WriteLine("Next value is " + 
                         ob.next); 
 
    Console.WriteLine("\nResetting to 0"); 
    ob.next = 0; 
 
    // access series through an indexer 
    for(int i=0; i < 5; i++) 
      Console.WriteLine("Next value is " + ob[i]); 
  } 
}


A safe method of determining whether a class implements a particular interface

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
//  ISample.cs - Demonstrates a safe method of determining whether a class
//               implements a particular interface
//               Compile this program with the following command line:
//                   C:>csc isample.cs
//
namespace nsInterfaceSample
{
    using System;
    public class InterfaceSample
    {
        static public void Main ()
        {
// Declare an instance of the clsSample class
            clsSample samp = new clsSample();
//  Test whether clsSample supports the IDisposable interface
            if (samp is IDisposable)
            {
//  If true, it is safe to call the Dispose() method
                IDisposable obj = (IDisposable) samp;
                obj.Dispose ();
            }
        }
    }
    class clsSample : IDisposable
    {
//  Implement the IDispose() function
        public void Dispose ()
        {
            Console.WriteLine ("Called Dispose() in clsSample");
        }
    }
}


Demonstrates the use of a simple interface

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// IntrFace.cs -- demonstrates the use of a simple interface
//
//                Compile this program with the following command line:
//                    C:>csc IntrFace.cs
using System;
namespace nsInterface
{
    interface IPlane
    {
        double Area
        {
            get;
        }
    }
    interface ISolid
    {
        double Volume
        {
            get;
        }
    }
    class clsCircle : IPlane
    {
        public clsCircle (double radius)
        {
            m_Radius = radius;
        }
        public double Area
        {
            get {return (3.14159 * m_Radius * m_Radius);}
        }
        private double m_Radius;

        public override string ToString ()
        {
            return ("Area = " + Area);
        }
    }
    class clsSphere : IPlane, ISolid
    {
        public clsSphere (double radius)
        {
            m_Radius = radius;
        }
        public double Area
        {
            get {return (4 * 3.14159 * m_Radius * m_Radius);}
        }
        public double Volume
        {
            get {return (4 * 3.14159 * m_Radius * m_Radius * m_Radius / 3);}
        }
        private double m_Radius;
        public override string ToString ()
        {
            return ("Area = " + Area + ", " + "Volume = " + Volume);
        }
    }
    public class IntrFace
    {
        static public void Main ()
        {
            clsCircle circle = new clsCircle (14.2);
            clsSphere sphere = new clsSphere (16.8);
            Console.WriteLine ("For the circle: " + circle);
            Console.WriteLine ("For the sphere: " + sphere);
        }
    }
}


Demonstrate the ByTwos interface

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System; 
public interface ISeries { 
  int getNext(); // return next number in series 
  void reset(); // restart 
  void setStart(int x); // set starting value 
}
// Implement ISeries. 
class ByTwos : ISeries { 
  int start; 
  int val; 
 
  public ByTwos() { 
    start = 0; 
    val = 0; 
  }  
 
  public int getNext() { 
    val += 2; 
    return val; 
  } 
 
  public void reset() { 
    val = start; 
  } 
 
  public void setStart(int x) { 
    start = x; 
    val = start; 
  } 
}
// Demonstrate the ByTwos interface. 
 
public class SeriesDemo { 
  public static void Main() { 
    ByTwos ob = new ByTwos(); 
 
    for(int i=0; i < 5; i++) 
      Console.WriteLine("Next value is " + 
                         ob.getNext()); 
 
    Console.WriteLine("\nResetting"); 
    ob.reset(); 
    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()); 
  } 
}


Demonstrate the ByTwos interface 2

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System; 
public interface ISeries { 
  int getNext(); // return next number in series 
  void reset(); // restart 
  void setStart(int x); // set starting value 
}
// Use ISeries to generate a sequence of even numbers. 
class ByTwos : ISeries { 
  int start; 
  int val; 
 
  public ByTwos() { 
    start = 0; 
    val = 0; 
  }  
 
  public int getNext() { 
    val += 2; 
    return val; 
  } 
 
  public void reset() { 
    val = start; 
  } 
 
  public void setStart(int x) { 
    start = x; 
    val = start; 
  } 
} 
 
// Use ISeries to implement a series of prime numbers.  
class Primes : ISeries {  
  int start;  
  int val;  
  
  public Primes() {  
    start = 2;  
    val = 2;  
  }   
  
  public int getNext() {  
    int i, j; 
    bool isprime; 
 
    val++; 
    for(i = val; i < 1000000; i++) { 
      isprime = true; 
      for(j = 2; j < (i/j + 1); j++) { 
        if((i%j)==0) { 
          isprime = false; 
          break; 
        } 
      } 
      if(isprime) { 
        val = i; 
        break; 
      } 
    } 
    return val;        
  }  
  
  public void reset() {  
    val = start;  
  }  
  
  public void setStart(int x) {  
    start = x;  
    val = start;  
  }  
} 
 
public class SeriesDemo2 { 
  public static void Main() { 
    ByTwos twoOb = new ByTwos(); 
    Primes primeOb = new Primes(); 
    ISeries ob; 
 
    for(int i=0; i < 5; i++) { 
      ob = twoOb; 
      Console.WriteLine("Next ByTwos value is " + 
                          ob.getNext()); 
      ob = primeOb; 
      Console.WriteLine("Next prime number is " + 
                          ob.getNext()); 
    } 
  } 
}


Explicitly implement an interface member

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Explicitly implement an interface member. 
 
using System; 
 
interface IEven { 
  bool isOdd(int x); 
  bool isEven(int x); 
} 
 
class MyClass : IEven { 
  // explicit implementation 
  bool IEven.isOdd(int x) { 
    if((x%2) != 0) return true; 
    else return false; 
  } 
 
  // normal implementation 
  public bool isEven(int x) { 
    IEven o = this; // reference to invoking object 
 
    return !o.isOdd(x); 
  } 
} 
 
public class Demo { 
  public static void Main() { 
    MyClass ob = new MyClass(); 
    bool result; 
 
    result = ob.isEven(4); 
    if(result) Console.WriteLine("4 is even."); 
    else Console.WriteLine("3 is odd."); 
 
    // result = ob.isOdd(); // Error, not exposed 
  } 
}


illustrates an explicit interface member implementation

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_7.cs illustrates an explicit interface member
  implementation
*/
using System;

// define the IDrivable interface
public interface IDrivable
{
  void TurnLeft();
}

// define the ISteerable interface
public interface ISteerable
{
  void TurnLeft();
}
// Car class implements the IMovable interface
class Car : IDrivable, ISteerable
{
  // explicitly implement the TurnLeft() method of the IDrivable interface
  void IDrivable.TurnLeft()
  {
    Console.WriteLine("IDrivable implementation of TurnLeft()");
  }
  // implement the TurnLeft() method of the ISteerable interface
  public void TurnLeft()
  {
    Console.WriteLine("ISteerable implementation of TurnLeft()");
  }
}

public class Example8_7
{
  public static void Main()
  {
    // create a Car object
    Car myCar = new Car();
    // call myCar.TurnLeft()
    Console.WriteLine("Calling myCar.TurnLeft()");
    myCar.TurnLeft();
    // cast myCar to IDrivable
    IDrivable myDrivable = myCar as IDrivable;
    Console.WriteLine("Calling myDrivable.TurnLeft()");
    myDrivable.TurnLeft();
    // cast myCar to ISteerable
    ISteerable mySteerable = myCar as ISteerable;
    Console.WriteLine("Calling mySteerable.TurnLeft()");
    mySteerable.TurnLeft();
  }
}


illustrates casting an object to an interface

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_4.cs illustrates casting an object
  to an interface
*/
using System;

// define the IDrivable interface
interface IDrivable
{
  // method declarations
  void Start();
  void Stop();
  // property declaration
  bool Started
  {
    get;
  }
}

// Car class implements the IDrivable interface
class Car : IDrivable
{
  // declare the underlying field used by the Started property
  private bool started = false;
  // implement the Start() method
  public void Start()
  {
    Console.WriteLine("car started");
    started = true;
  }
  // implement the Stop() method
  public void Stop()
  {
    Console.WriteLine("car stopped");
    started = false;
  }
  // implement the Started property
  public bool Started
  {
    get
    {
      return started;
    }
  }
  
}

public class Example8_4
{
  public static void Main()
  {
    // create a Car object
    Car myCar = new Car();
    // use the is operator to check that myCar supports the
    // IDrivable interface
    if (myCar is IDrivable)
    {
      Console.WriteLine("myCar supports IDrivable");
    }
    // cast the Car object to IDrivable
    IDrivable myDrivable = (IDrivable) myCar;
    // call myDrivable.Start()
    Console.WriteLine("Calling myDrivable.Start()");
    myDrivable.Start();
    Console.WriteLine("myDrivable.Started = " +
      myDrivable.Started);
    // call myDrivable.Stop()
    Console.WriteLine("Calling myDrivable.Stop()");
    myDrivable.Stop();
    Console.WriteLine("myDrivable.Started = " +
      myDrivable.Started);
    // cast the Car object to IDrivable using the as operator
    IDrivable myDrivable2 = myCar as IDrivable;
    if (myDrivable2 != null)
    {
      Console.WriteLine("Calling myDrivable2.Start()");
      myDrivable2.Start();
      Console.WriteLine("Calling myDrivable2.Stop()");
      myDrivable2.Stop();
      Console.WriteLine("myDrivable2.Started = " +
        myDrivable2.Started);
    }
  }
}


illustrates deriving an interface from multiple interfaces

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_6.cs illustrates deriving an
  interface from multiple interfaces
*/
using System;

public class Example8_6
{
  public static void Main()
  {
    // create a Car object
    Car myCar = new Car();
    // call myCar.Start()
    Console.WriteLine("Calling myCar.Start()");
    myCar.Start();
    // call myCar.TurnLeft()
    Console.WriteLine("Calling myCar.TurnLeft()");
    myCar.TurnLeft();
    // call myCar.Accelerate()
    Console.WriteLine("Calling myCar.Accelerate()");
    myCar.Accelerate();
  }
}

// define the IDrivable interface
public interface IDrivable
{
  // method declarations
  void Start();
  void Stop();
  // property declaration
  bool Started
  {
    get;
  }
}

// define the ISteerable interface
public interface ISteerable
{
  // method declarations
  void TurnLeft();
  void TurnRight();
}

// define the IMovable interface (derived from IDrivable and ISteerable)
public interface IMovable : IDrivable, ISteerable
{
  // method declarations
  void Accelerate();
  void Brake();
}

// Car class implements the IMovable interface
public class Car : IMovable
{
  // declare the underlying field used by the
  // Started property of the IDrivable interface
  private bool started = false;
  // implement the Start() method of the IDrivable interface
  public void Start()
  {
    Console.WriteLine("car started");
    started = true;
  }
  // implement the Stop() methodof the IDrivable interface
  public void Stop()
  {
    Console.WriteLine("car stopped");
    started = false;
  }
  // implement the Started property of the IDrivable interface
  public bool Started
  {
    get
    {
      return started;
    }
  }
  // implement the TurnLeft() method of the ISteerable interface
  public void TurnLeft()
  {
    Console.WriteLine("car turning left");
  }
  
  // implement the TurnRight() method of the ISteerable interface
  public void TurnRight()
  {
    Console.WriteLine("car turning right");
  }
  // implement the Accelerate() method of the IMovable interface
  public void Accelerate()
  {
    Console.WriteLine("car accelerating");
  }
  
  // implement the Brake() method of the IMovable interface
  public void Brake()
  {
    Console.WriteLine("car braking");
  }
}


illustrates deriving an interface from one interface

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_5.cs illustrates deriving an
  interface from one interface
*/
using System;

// define the IDrivable interface
interface IDrivable
{
  // method declarations
  void Start();
  void Stop();
  // property declaration
  bool Started
  {
    get;
  }
}

// define the IMovable interface (derived from IDrivable)
interface IMovable : IDrivable
{
  // method declarations
  void Accelerate();
  void Brake();
}

// Car class implements the IMovable interface
class Car : IMovable
{
  // declare the underlying field used by the
  // Started property of the IDrivable interface
  private bool started = false;
  // implement the Start() method of the IDrivable interface
  public void Start()
  {
    Console.WriteLine("car started");
    started = true;
  }
  // implement the Stop() methodof the IDrivable interface
  public void Stop()
  {
    Console.WriteLine("car stopped");
    started = false;
  }
  // implement the Started property of the IDrivable interface
  public bool Started
  {
    get
    {
      return started;
    }
  }
  // implement the Accelerate() method of the IMovable interface
  public void Accelerate()
  {
    Console.WriteLine("car accelerating");
  }
  
  // implement the Brake() method of the IMovable interface
  public void Brake()
  {
    Console.WriteLine("car braking");
  }
}

public class Example8_5
{
  public static void Main()
  {
    // create a Car object
    Car myCar = new Car();
    // call myCar.Start()
    Console.WriteLine("Calling myCar.Start()");
    myCar.Start();
    // call myCar.Accelerate()
    Console.WriteLine("Calling myCar.Accelerate()");
    myCar.Accelerate();
  }
}


illustrates implementing multiple interfaces

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_2.cs illustrates implementing multiple interfaces
*/
using System;

// define the IDrivable interface
public interface IDrivable
{
  // method declarations
  void Start();
  void Stop();
  // property declaration
  bool Started
  {
    get;
  }
}

// define the ISteerable interface
public interface ISteerable
{
  // method declarations
  void TurnLeft();
  void TurnRight();
}

// Car class implements the IMovable interface
class Car : IDrivable, ISteerable
{
  // declare the underlying field used by the
  // Started property of the IDrivable interface
  private bool started = false;
  // implement the Start() method of the IDrivable interface
  public void Start()
  {
    Console.WriteLine("car started");
    started = true;
  }
  // implement the Stop() methodof the IDrivable interface
  public void Stop()
  {
    Console.WriteLine("car stopped");
    started = false;
  }
  // implement the Started property of the IDrivable interface
  public bool Started
  {
    get
    {
      return started;
    }
  }
  // implement the TurnLeft() method of the ISteerable interface
  public void TurnLeft()
  {
    Console.WriteLine("car turning left");
  }
  
  // implement the TurnRight() method of the ISteerable interface
  public void TurnRight()
  {
    Console.WriteLine("car turning right");
  }
}

public class Example8_2
{
  public static void Main()
  {
    // create a Car object
    Car myCar = new Car();
    // call myCar.Start()
    Console.WriteLine("Calling myCar.Start()");
    myCar.Start();
    // call myCar.TurnLeft()
    Console.WriteLine("Calling myCar.TurnLeft()");
    myCar.TurnLeft();
  }
}


illustrates inheriting from a class and implementing multiple interfaces

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_3.cs illustrates inheriting from a class and
  implementing multiple interfaces
*/
using System;

interface IDrivable
{
  // method declarations
  void Start();
  void Stop();
  // property declaration
  bool Started
  {
    get;
  }
}

interface ISteerable
{
  // method declarations
  void TurnLeft();
  void TurnRight();
}

class MotorVehicle
{
  // declare the field
  private string model;
  // define a constructor
  public MotorVehicle(string model)
  {
    this.model = model;
  }
  // declare a property
  public string Model
  {
    get
    {
      return model;
    }
    set
    {
      model = value;
    }
  }
}

// Car class inherits from the MotorVehicle class and
// implements the IDrivable and ISteerable interfaces
class Car : MotorVehicle, IDrivable, ISteerable
{
  // declare the underlying field used by the
  // Started property of the IDrivable interface
  private bool started = false;
  // define a constructor
  public Car(string model) :
  base(model)   // calls the base class constructor
  {
    // do nothing
  }
  // implement the Start() method of the IDrivable interface
  public void Start()
  {
    Console.WriteLine("car started");
    started = true;
  }
  // implement the Stop() methodof the IDrivable interface
  public void Stop()
  {
    Console.WriteLine("car stopped");
    started = false;
  }
  // implement the Started property of the IDrivable interface
  public bool Started
  {
    get
    {
      return started;
    }
  }
  // implement the TurnLeft() method of the ISteerable interface
  public void TurnLeft()
  {
    Console.WriteLine("car turning left");
  }
  
  // implement the TurnRight() method of the ISteerable interface
  public void TurnRight()
  {
    Console.WriteLine("car turning right");
  }
}

public class Example8_3
{
  public static void Main()
  {
    // create a Car object
    Car myCar = new Car("MR2");
    Console.WriteLine("myCar.Model = " + myCar.Model);
    // call myCar.Start()
    Console.WriteLine("Calling myCar.Start()");
    myCar.Start();
    // call myCar.TurnLeft()
    Console.WriteLine("Calling myCar.TurnLeft()");
    myCar.TurnLeft();
  }
}


illustrates interface member hiding

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_8.cs illustrates interface member hiding
*/
using System;

// define the IDrivable interface
public interface IDrivable
{
  void TurnLeft();
}

// define the ISteerable interface (derived from IDrivable)
public interface ISteerable : IDrivable
{
  new void TurnLeft();  // hides TurnLeft() in IDrivable
}
// Car class implements the IMovable interface
class Car : ISteerable
{
  // explicitly implement the TurnLeft() method of the ISteerable interface
  void ISteerable.TurnLeft()
  {
    Console.WriteLine("ISteerable implementation of TurnLeft()");
  }
  // implement the TurnLeft() method of the IDrivable interface
  public void TurnLeft()
  {
    Console.WriteLine("IDrivable implementation of TurnLeft()");
  }
}

public class Example8_8
{
  public static void Main()
  {
    // create a Car object
    Car myCar = new Car();
    // call myCar.TurnLeft()
    Console.WriteLine("Calling myCar.TurnLeft()");
    myCar.TurnLeft();
    // cast myCar to ISteerable
    ISteerable mySteerable = myCar as ISteerable;
    Console.WriteLine("Calling mySteerable.TurnLeft()");
    mySteerable.TurnLeft();
    // cast myCar to IDrivable
    IDrivable myDrivable = myCar as IDrivable;
    Console.WriteLine("Calling myDrivable.TurnLeft()");
    myDrivable.TurnLeft();
  }
}


illustrates interfaces

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_1.cs illustrates interfaces
*/
using System;

// define the IDrivable interface
public interface IDrivable
{
  // method declarations
  void Start();
  void Stop();
  // property declaration
  bool Started
  {
    get;
  }
}

// Car class implements the IDrivable interface
class Car : IDrivable
{
  // declare the underlying field used by the Started property
  private bool started = false;
  // implement the Start() method
  public void Start()
  {
    Console.WriteLine("car started");
    started = true;
  }
  // implement the Stop() method
  public void Stop()
  {
    Console.WriteLine("car stopped");
    started = false;
  }
  // implement the Started property
  public bool Started
  {
    get
    {
      return started;
    }
  }
  
}

public class Example8_1
{
  public static void Main()
  {
    // create a Car object
    Car myCar = new Car();
    // call myCar.Start()
    myCar.Start();
    Console.WriteLine("myCar.Started = " + myCar.Started);
    // call myCar.Stop()
    myCar.Stop();
    Console.WriteLine("myCar.Started = " + myCar.Started);
  }
}


Interface casting

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace InterfaceDemo
 {
     interface IStorable
     {
         void Read();
         void Write(object obj);
         int Status { get; set; }
     }
     // here"s the new interface
     interface ICompressible
     {
         void Compress();
         void Decompress();
     }

     // Document implements both interfaces
     class Document : IStorable
     {
         // the document constructor
         public Document(string s)
         {
             Console.WriteLine("Creating document with: {0}", s);
         }
         // implement IStorable
         public void Read()
         {
             Console.WriteLine(
                 "Implementing the Read Method for IStorable");
         }
         public void Write(object o)
         {
             Console.WriteLine(
                 "Implementing the Write Method for IStorable");
         }
         public int Status
         {
             get { return status; }
             set { status = value; }
         }
         // hold the data for IStorable"s Status property
         private int status = 0;
     }

    public class TesterInterfaceDemoCasting
    {
       [STAThread]
       static void Main()
       {
           Document doc = new Document("Test Document");
           // only cast if it is safe
           if (doc is IStorable)
           {
               IStorable isDoc = (IStorable) doc;
               isDoc.Read();
           }
           else
           {
               Console.WriteLine("Could not cast to IStorable");
           }
           // this test will fail
           if (doc is ICompressible)
           {
               ICompressible icDoc = (ICompressible) doc;
               icDoc.rupress();
           }
           else
           {
               Console.WriteLine("Could not cast to ICompressible");
           }       }
    }
 }


Interface demo

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace InterfaceDemo
 {
     // define the interface
     interface IStorable
     {
         void Read();
         void Write(object obj);
         int Status { get; set; }
     }
     // create a Document class that implements the IStorable interface
     class Document : IStorable
     {
         public Document(string s)
         {
             Console.WriteLine("Creating document with: {0}", s);
         }
         // implement the Read method
         public void Read()
         {
             Console.WriteLine(
                 "Implementing the Read Method for IStorable");
         }
         // implement the Write method
         public void Write(object o)
         {
             Console.WriteLine(
                 "Implementing the Write Method for IStorable");
         }
         // implement the property
         public int Status
         {
             get{ return status; }
             set{ status = value; }
         }
         // store the value for the property
         private int status = 0;
     }
    public class TesterInterfaceDemo
    {
       public void Run()
       {
           Document doc = new Document("Test Document");
           doc.Status = -1;
           doc.Read();
           Console.WriteLine("Document Status: {0}", doc.Status);
       }
       [STAThread]
       static void Main()
       {
          TesterInterfaceDemo t = new TesterInterfaceDemo();
          t.Run();
       }
    }
 }


Interface demo: implements two interfaces

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace InterfaceDemo
 {
     interface IStorable
     {
         void Read();
         void Write(object obj);
         int Status { get; set; }
     }
     // here"s the new interface
     interface ICompressible
     {
         void Compress();
         void Decompress();
     }

     // Document implements both interfaces
     class Document : IStorable, ICompressible
     {
         // the document constructor
         public Document(string s)
         {
             Console.WriteLine("Creating document with: {0}", s);
         }
         // implement IStorable
         public void Read()
         {
             Console.WriteLine(
                 "Implementing the Read Method for IStorable");
         }
         public void Write(object o)
         {
             Console.WriteLine(
                 "Implementing the Write Method for IStorable");
         }
         public int Status
         {
             get { return status; }
             set { status = value; }
         }
         // implement ICompressible
         public void Compress()
         {
             Console.WriteLine("Implementing Compress");
         }
 
         public void Decompress()
         {
             Console.WriteLine("Implementing Decompress");
         }

         // hold the data for IStorable"s Status property
         private int status = 0;
     }

    public class TesterInterfaceDemo2
    {
       public void Run()
       {
           Document doc = new Document("Test Document");
           doc.Status = -1;
           doc.Read();
           doc.rupress();
           Console.WriteLine("Document Status: {0}", doc.Status);
       }
       [STAThread]
       static void Main()
       {
          TesterInterfaceDemo2 t = new TesterInterfaceDemo2();
          t.Run();
       }
    }
 }


Interfaces:Working with Interfaces

/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 10 - Interfaces\Working with Interfaces
// copyright 2000 Eric Gunnerson
using System;
public class WorkingwithInterfaces
{
    public static void Main()
    {
        DiagramObject[] dArray = new DiagramObject[100];
        
        dArray[0] = new DiagramObject();
        dArray[1] = new TextObject("Text Dude");
        dArray[2] = new TextObject("Text Backup");
        
        // array gets initialized here, with classes that
        // derive from DiagramObject. Some of them implement
        // IScalable.
        
        foreach (DiagramObject d in dArray)
        {
            if (d is IScalable)
            {
                IScalable scalable = (IScalable) d;
                scalable.ScaleX(0.1F);
                scalable.ScaleY(10.0F);
            }
        }
    }
}
interface IScalable
{
    void ScaleX(float factor);
    void ScaleY(float factor);
}
public class DiagramObject
{
    public DiagramObject() {}
}
public class TextObject: DiagramObject, IScalable
{
    public TextObject(string text)
    {
        this.text = text;
    }
    // implementing IScalable.ScaleX()
    public void ScaleX(float factor)
    {
        Console.WriteLine("ScaleX: {0} {1}", text, factor);
        // scale the object here.
    }
    
    // implementing IScalable.ScaleY()
    public void ScaleY(float factor)
    {
        Console.WriteLine("ScaleY: {0} {1}", text, factor);
        // scale the object here.
    }
    
    private string text;
}


Interface with event

 
using System;
public delegate void AlarmEvent(IAlarm sender);
public interface IAlarm {
    event AlarmEvent IssueAlarm;
}
abstract class MyStuff : ICloneable {
    public object Clone() {
        return null;
    }
    public void DoStuff() {
    }
}
interface IFoo {
    void DoStuff();
}
interface IBar {
    void DoStuff();
}
interface ITest {
    void DoSomething();
    int DoSomethingElse();
}
class MyClass : IFoo, IBar {
    void IFoo.DoStuff() {
    }
    void IBar.DoStuff() {
    }
}
class MainClass : IComparable {
    public int CompareTo(object other) {
        return -1;
    }
    static int Main(string[] args) {
        MainClass c = new MainClass();
        MainClass c2 = new MainClass();
        if (c.rupareTo(c2) == 0)
            return 0;
        MyClass c3 = new MyClass();
        return 1;
    }
}


Interface with method name conflicts

 
using System;
public delegate void AlarmEvent(IAlarm sender);
public interface IAlarm {
    event AlarmEvent IssueAlarm;
}
abstract class MyStuff : ICloneable {
    public object Clone() {
        return null;
    }
    public void DoStuff() {
    }
}
interface IFoo {
    void DoStuff();
}
interface IBar {
    void DoStuff();
}
interface ITest {
    void DoSomething();
    int DoSomethingElse();
}
class MyClass : IFoo, IBar {
    void IFoo.DoStuff() {
    }
    void IBar.DoStuff() {
    }
}
class MainClass : IComparable {
    public int CompareTo(object other) {
        return -1;
    }
    static int Main(string[] args) {
        MainClass c = new MainClass();
        MainClass c2 = new MainClass();
        if (c.rupareTo(c2) == 0)
            return 0;
        MyClass c3 = new MyClass();
        return 1;
    }
}


One interface can inherit another

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// One interface can inherit another. 
 
using System; 
 
public interface A { 
  void meth1(); 
  void meth2(); 
} 
 
// B now includes meth1() and meth2() -- it adds meth3(). 
public interface B : A { 
  void meth3(); 
} 
 
// This class must implement all of A and B 
class MyClass : B { 
  public void meth1() { 
    Console.WriteLine("Implement meth1()."); 
  } 
 
  public void meth2() { 
    Console.WriteLine("Implement meth2()."); 
  } 
 
  public void meth3() { 
    Console.WriteLine("Implement meth3()."); 
  } 
} 
 
public class IFExtend { 
  public static void Main() { 
    MyClass ob = new MyClass(); 
 
    ob.meth1(); 
    ob.meth2(); 
    ob.meth3(); 
  } 
}


Overriding Interfaces

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace OverridingInterfaces
 {
     interface IStorable
     {
         void Read();
         void Write();
     }
     // Simplify Document to implement only IStorable
     class Document : IStorable
     {
         // the document constructor
         public Document(string s)
         {
             Console.WriteLine(
                 "Creating document with: {0}", s);
         }
         // Make read virtual
         public virtual void Read()
         {
             Console.WriteLine(
                 "Document Read Method for IStorable");
         }
         // NB: Not virtual!
         public void Write()
         {
             Console.WriteLine(
                 "Document Write Method for IStorable");
         }
     }
     // Derive from Document
     class Note : Document
     {
         public Note(string s):
             base(s)
         {
             Console.WriteLine(
                 "Creating note with: {0}", s);
         }
         // override the Read method
         public override void Read()
         {
             Console.WriteLine(
                 "Overriding the Read method for Note!");
         }
         // implement my own Write method
         public new void Write()
         {
             Console.WriteLine(
                 "Implementing the Write method for Note!");
         }
     }
     public class OverridingInterfacesTester
     {
         public void Run()
         {
             // Create a Document object
             Document theNote = new Note("Test Note");
             // direct call to the methods
             theNote.Read();
             theNote.Write();
             Console.WriteLine("\n");
             // cast the Document to IStorable
             IStorable isNote = theNote as IStorable;
             if (isNote != null)
             {
                 isNote.Read();
                 isNote.Write();
             }
             Console.WriteLine("\n");
             // create a note object
             Note note2 = new Note("Second Test");
             // directly call the methods
             note2.Read();
             note2.Write();
             Console.WriteLine("\n");
             // Cast the note to IStorable
             IStorable isNote2 = note2 as IStorable;
             if (isNote != null)
             {
                 isNote2.Read();
                 isNote2.Write();
             }

         }
         static void Main()
         {
             OverridingInterfacesTester t = new OverridingInterfacesTester();
             t.Run();
         }
     }
 }


Overriding Interfaces: Tester Overriding InterfacesAs

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace OverridingInterfaces
 {
     interface IStorable
     {
         void Read();
         void Write();
     }
     interface ITalk
     {
         void Talk();
         void Read();
     }

     // Modify Document to also implement ITalk
     class Document : IStorable, ITalk
     {
         // the document constructor
         public Document(string s)
         {
             Console.WriteLine(
                 "Creating document with: {0}", s);
         }
         // Implicit implementation
         public virtual void Read()
         {
             Console.WriteLine(
                 "Document Read Method for IStorable");
         }
         public void Write()
         {
             Console.WriteLine(
                 "Document Write Method for IStorable");
         }
         // Explicit implementation
         void ITalk.Read()
         {
             Console.WriteLine("Implementing ITalk.Read");
         }
         public void Talk()
         {
             Console.WriteLine("Implementing ITalk.Talk");
         }
     }
    public class TesterOverridingInterfacesAs
    {
       [STAThread]
       static void Main()
       {
           // Create a Document object
           Document theDoc = new Document("Test Document");
           IStorable isDoc = theDoc as IStorable;
           if (isDoc != null)
           {
               isDoc.Read();
           }
           // Cast to an ITalk interface
           ITalk itDoc = theDoc as ITalk;
           if (itDoc != null)
           {
               itDoc.Read();
           }
           theDoc.Read();
           theDoc.Talk();
       }
    }
 }


Reimplementation of Interfaces

 
public interface IZ {
    void MethodA();
    void MethodB();
}
public class MyClass : IZ {
    public void MethodA() {
    }
    public void MethodB() {
    }
}
public class YClass : MyClass, IZ {
    public new void MethodA() {
    }
    public new void MethodB() {
    }
}


Two class inherit one interface

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System; 
// An encryption interface. 
public interface ICipher { 
  string encode(string str); 
  string decode(string str); 
}
/* A simple implementation of ICipher that codes 
   a message by shifting each character 1 position 
   higher.  Thus, A becomes B, and so on. */ 
class SimpleCipher : ICipher { 
     
  // Return an encoded string given plaintext. 
  public string encode(string str) { 
    string ciphertext = ""; 
 
    for(int i=0; i < str.Length; i++) 
      ciphertext = ciphertext + (char) (str[i] + 1); 
 
    return ciphertext; 
  } 
 
  // Return an decoded string given ciphertext. 
  public string decode(string str) { 
    string plaintext = ""; 
 
    for(int i=0; i < str.Length; i++) 
      plaintext = plaintext + (char) (str[i] - 1); 
 
    return plaintext; 
  } 
} 
 
/* This implementation of ICipher uses bit 
   manipulations and key. */ 
class BitCipher : ICipher { 
  ushort key; 
 
  // Specify a key when constructing BitCiphers. 
  public BitCipher(ushort k) { 
    key = k; 
  } 
     
  // Return an encoded string given plaintext. 
  public string encode(string str) { 
    string ciphertext = ""; 
 
    for(int i=0; i < str.Length; i++) 
      ciphertext = ciphertext + (char) (str[i] ^ key); 
 
    return ciphertext; 
  } 
 
  // Return an decoded string given ciphertext. 
  public string decode(string str) { 
    string plaintext = ""; 
 
    for(int i=0; i < str.Length; i++) 
      plaintext = plaintext + (char) (str[i] ^ key); 
 
    return plaintext; 
  } 
}
// Demonstrate ICipher. 
 
public class ICipherDemo { 
  public static void Main() { 
    ICipher ciphRef; 
    BitCipher bit = new BitCipher(27); 
    SimpleCipher sc = new SimpleCipher(); 
 
    string plain; 
    string coded; 
 
    // first, ciphRef refers to the simple cipher 
    ciphRef = sc; 
 
    Console.WriteLine("Using simple cipher."); 
 
    plain = "testing"; 
    coded = ciphRef.encode(plain); 
    Console.WriteLine("Cipher text: " + coded); 
 
    plain = ciphRef.decode(coded); 
    Console.WriteLine("Plain text: " + plain); 
 
    // now, let ciphRef refer to the bitwise cipher 
    ciphRef = bit; 
 
    Console.WriteLine("\nUsing bitwise cipher."); 
 
    plain = "testing"; 
    coded = ciphRef.encode(plain); 
    Console.WriteLine("Cipher text: " + coded); 
 
    plain = ciphRef.decode(coded); 
    Console.WriteLine("Plain text: " + plain); 
  } 
}


Use a property in an interface

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use a property in an interface. 
 
using System; 
 
public interface ISeries { 
  // an interface property 
  int next { 
    get; // return the next number in series 
    set; // set next number 
  } 
} 
 
// Implement ISeries. 
class ByTwos : ISeries { 
  int val; 
 
  public ByTwos() { 
    val = 0; 
  }  
 
  // get or set value 
  public int next { 
    get {  
      val += 2; 
      return val; 
    } 
    set { 
      val = value; 
    } 
  } 
} 
 
// Demonstrate an interface property. 
public class SeriesDemo3 { 
  public static void Main() { 
    ByTwos ob = new ByTwos(); 
 
    // access series through a property 
    for(int i=0; i < 5; i++) 
      Console.WriteLine("Next value is " + ob.next); 
 
    Console.WriteLine("\nStarting at 21"); 
    ob.next = 21; 
    for(int i=0; i < 5; i++) 
      Console.WriteLine("Next value is " + ob.next); 
  } 
}


Use explicit implementation to remove ambiguity

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Use explicit implementation to remove ambiguity. 
 
using System; 
 
interface IMyIF_A { 
  int meth(int x); 
} 
 
interface IMyIF_B { 
  int meth(int x); 
} 
 
// MyClass implements both interfaces. 
class MyClass : IMyIF_A, IMyIF_B { 
 
  // explicitly implement the two meth()s 
  int IMyIF_A.meth(int x) { 
    return x + x; 
  } 
  int IMyIF_B.meth(int x) { 
    return x * x; 
  } 
 
  // call meth() through an interface reference. 
  public int methA(int x){ 
    IMyIF_A a_ob; 
    a_ob = this; 
    return a_ob.meth(x); // calls IMyIF_A 
  } 
 
  public int methB(int x){ 
    IMyIF_B b_ob; 
    b_ob = this; 
    return b_ob.meth(x); // calls IMyIF_B 
  } 
} 
 
public class FQIFNames { 
  public static void Main() { 
    MyClass ob = new MyClass(); 
 
    Console.Write("Calling IMyIF_A.meth(): "); 
    Console.WriteLine(ob.methA(3)); 
 
    Console.Write("Calling IMyIF_B.meth(): "); 
    Console.WriteLine(ob.methB(3)); 
  } 
}


Using interface 3

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System; 
// An encryption interface. 
public interface ICipher { 
  string encode(string str); 
  string decode(string str); 
}
/* A simple implementation of ICipher that codes 
   a message by shifting each character 1 position 
   higher.  Thus, A becomes B, and so on. */ 
class SimpleCipher : ICipher { 
     
  // Return an encoded string given plaintext. 
  public string encode(string str) { 
    string ciphertext = ""; 
 
    for(int i=0; i < str.Length; i++) 
      ciphertext = ciphertext + (char) (str[i] + 1); 
 
    return ciphertext; 
  } 
 
  // Return an decoded string given ciphertext. 
  public string decode(string str) { 
    string plaintext = ""; 
 
    for(int i=0; i < str.Length; i++) 
      plaintext = plaintext + (char) (str[i] - 1); 
 
    return plaintext; 
  } 
} 
 
/* This implementation of ICipher uses bit 
   manipulations and key. */ 
class BitCipher : ICipher { 
  ushort key; 
 
  // Specify a key when constructing BitCiphers. 
  public BitCipher(ushort k) { 
    key = k; 
  } 
     
  // Return an encoded string given plaintext. 
  public string encode(string str) { 
    string ciphertext = ""; 
 
    for(int i=0; i < str.Length; i++) 
      ciphertext = ciphertext + (char) (str[i] ^ key); 
 
    return ciphertext; 
  } 
 
  // Return an decoded string given ciphertext. 
  public string decode(string str) { 
    string plaintext = ""; 
 
    for(int i=0; i < str.Length; i++) 
      plaintext = plaintext + (char) (str[i] ^ key); 
 
    return plaintext; 
  } 
}
// Use ICipher. 
 
// A class for storing unlisted telephone numbers. 
class UnlistedPhone { 
  string pri_name;   // supports name property 
  string pri_number; // supports number property 
 
  ICipher crypt; // reference to encryption object 
 
  public UnlistedPhone(string name, string number, ICipher c) 
  { 
    crypt = c; // store encryption object 
 
    pri_name = crypt.encode(name); 
    pri_number = crypt.encode(number); 
  } 
 
  public string Name { 
    get { 
      return crypt.decode(pri_name); 
    } 
    set { 
      pri_name = crypt.encode(value); 
    } 
  } 
 
  public string Number { 
    get { 
      return crypt.decode(pri_number); 
    } 
    set { 
      pri_number = crypt.encode(value); 
    } 
  } 
} 
 
// Demonstrate UnlistedPhone 
public class UnlistedDemo { 
  public static void Main() { 
    UnlistedPhone phone1 = 
        new UnlistedPhone("Tom", "555-3456", new BitCipher(27));  
    UnlistedPhone phone2 = 
        new UnlistedPhone("Mary", "555-8891", new BitCipher(9)); 
 
 
    Console.WriteLine("Unlisted number for " +  
                      phone1.Name + " is " + 
                      phone1.Number);  
 
    Console.WriteLine("Unlisted number for " +  
                      phone2.Name + " is " + 
                      phone2.Number);  
  } 
}