ex-08-03

来自「Programming Csharp Source Code(代码) Prog」· 代码 · 共 84 行

TXT
84
字号
//Example 08-03: Using the is operator

using System;

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 IStorable
public class Document : IStorable
{
   public Document(string s) 
   {
      Console.WriteLine(
         "Creating document with: {0}", s);
        
   }

   // IStorable.Read
   public void Read()
   {
      Console.WriteLine(
         "Implementing the Read Method for IStorable");        
   }

   // IStorable.Write
   public void Write(object o)
   {
      Console.WriteLine(
         "Implementing the Write Method for IStorable");  
   }

   // IStorable.Status
   public int Status
   {
      get
      {
         return status;
      }

      set
      {
         status = value;
      }
   }

   private int status = 0;
}

public class Tester
{
 
   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();
      }

      // this test will fail
      if (doc is ICompressible)
      {
         ICompressible icDoc = (ICompressible) doc;
         icDoc.Compress();
      }
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?