📄 5.4.txt
字号:
Listing 5.4 ConsoleMenu Class Fires the OnMenuEvent Event
using System;
using System.Collections;
namespace _7_AddingEvents
{
class Class1
{
static void Main(string[] args)
{
}
}
class ConsoleMenu
{ ArrayList menuItems = new ArrayList();
bool quitMenu = false;
// menu item event handler delegate
public delegate void MenuEventHandler( object sender, string[] args );
// event fired when user selects a menu item
public event MenuEventHandler OnMenuEvent;
// adds a menu item to the internal ArrayList
public void AddMenuItem( string text )
{
menuItems.Add( text );
}
public void QuitMenu()
{
quitMenu = true;
}
public void DisplayMenu()
{
string input;
do
{
int idx = 1;
int choice = 0;
// display each menu item string prefaced by its index value
foreach( string menuChoice in menuItems )
Console.WriteLine( “{0}: {1}”, idx++, menuChoice );
Console.Write( “Enter choice: “ );
// get users input and convert to integer
input = Console.ReadLine();
choice = Int32.Parse( input[0].ToString() );
if( choice > 0 && choice <= menuItems.Count )
{
// build event arguments
string[] args = new string[2];
args[0] = input[0].ToString();
args[1] =
menuItems[Int32.Parse(input[0].ToString())-1].ToString();
// fire event to be handled by client using this class
OnMenuEvent( this, args);
}
else
{
Console.WriteLine( “Invalid choice!\n” );
}
} while ( quitMenu == false );
quitMenu = false;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -