ch5_6.cs

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

CS
83
字号
using System;
using System.Collections;

public delegate bool HandleKeyword( string key );

public class Parser
{
   Hashtable parseTable;
   
   public Parser()
   {
      parseTable = new Hashtable();
   }
   
   public void AddKeywordHandler( string key, HandleKeyword handler )
   {
      parseTable.Add( key, handler );
   }
   
   public bool ParseKeyword( string key )
   {
      HandleKeyword func = (HandleKeyword)parseTable[ key ];
      if ( func == null )
         return false;
	 
      return func( key );
   }
}

public class HandleHello
{
   public static bool HandleIt( string s )
   {
      Console.WriteLine( "HandleHello::HandleIt {0}", s );
      return true;
   }
}

public class HandleGoodbye
{
   public static bool HandleIt( string s )
   {
      Console.WriteLine( "HandleGooebye::HandleIt {0}", s );
      return true;
   }
}

public class HandleWhy
{
   public static bool HandleIt( string s )
   {
      Console.WriteLine( "HandleWhy::HandleIt {0}", s );
      return true;
   }
}

class CH5_6
{
   public static void Main(string[] args)
   {
      // Create the objects
      Parser p = new Parser();
      
      // Add the handlers
      p.AddKeywordHandler( "hello", new HandleKeyword(HandleHello.HandleIt) );
      p.AddKeywordHandler( "goodbye", new HandleKeyword(HandleGoodbye.HandleIt) );
      p.AddKeywordHandler( "why", new HandleKeyword(HandleWhy.HandleIt) );
      
      // Do the parsing
      for ( int i=0; i<args.Length; ++i )
         if ( p.ParseKeyword( args[i] ) == false )
	    Console.WriteLine("Unknown keyword {0}", args[i] );
   }
}



      
      

   
   

⌨️ 快捷键说明

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