ch2_14.cs

来自「《c#技术内幕代码》」· CS 代码 · 共 92 行

CS
92
字号
using System;
class Book
{
   private string fTitle;
   private string fAuthor;
   private string fSubject;
   private string fDescription;
   
   public Book( string title, string author, string subj,
                    string descr )
   {
      fTitle = title;
      fAuthor = author;
      fSubject = subj;
      fDescription = descr;
   }
   public Book()
   {
   }
   
   // Define an indexer.
   public string this[string index]
   {
      get
      {
         if ( index == "Title" )
	    return fTitle;
	 if ( index == "Author" )
	    return fAuthor;
	 if ( index == "Subject" )
	    return fSubject;
	 if ( index == "Description" )
	    return fDescription;
	 return "Unknown";
      }
      set
      {
         if ( index == "Title" )
	    fTitle = value;
	 if ( index == "Author" )
	    fAuthor = value;
	 if ( index == "Subject" )
	    fSubject = value;
	 if ( index == "Description" )
	    fDescription = value;
      }
   }
   public string this[int index]
   {
      get
      {
         if ( index == 1 )
	    return fTitle;
	 if ( index == 2 )
	    return fAuthor;
	 if ( index == 3 )
	    return fSubject;
	 if ( index == 4 )
	    return fDescription;
	 return "Unknown";
      }
      set
      {
         if ( index == 1 )
	    fTitle = value;
	 if ( index == 2 )
	    fAuthor = value;
	 if ( index == 3 )
	    fSubject = value;
	 if ( index == 4 )
	    fDescription = value;
      }
   }
}

class CH2_14 
{
   static public void Main()
   {
      Book b = new Book("C# Black Book", "Matt Telles",
                    "C# programming", "A great book");
		    
      Console.WriteLine("Book Title: {0}", b["Title"]);
      Book b2 = new Book();
      b2["Title"] = "The Second Volume";
      b2[2] = "Another Author";
      Console.WriteLine("Book Title: {0}", b2["Title"]);
   }
}


⌨️ 快捷键说明

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