C#教程第五课:方法

添加人:gamefriends二级(854分)   添加时间:2007-09-12    阅读次数:1468  收藏此教程

本节课向你介绍C#的方法,其目的是:
1.了解方法的结构格式

2.了解静态和实例方法之间的区别

3.学会实例对象的使用

4.学会如何调用实例化的对象

5.学会方法的四种参数类型的使用

6.学会使用"this"引用

以往,对于每个程序来说,所有的工作都在Main()方法中实现。这对于功能简单的程序是合适的,因为仅仅用来学习一些概念。有个更好的方法来组织你的程序,那就是使用方法。方法是很有用的,因为方法可以让你在不同的单元中分开设计你的逻辑模块。

方法的结构格式如下:

属性 修饰符 返回值类型 方法名(参数) { 语句 }

我们将在后面的课程中,讨论属性和修饰符。方法的返回值可以是任何一种C#的数据类型,该返回值可以赋给变量,以便在程序的后面部分使用。方法名是唯一,可以被程序调用。为使得你的代码变得更容易理解和记忆,方法的取名可以同所要进行的操作联系起来。你可以传递数据给方法,也可以从方法中返回数据。它们由大括号包围起来。大括号中的语句实现了方法的功能。

1.清单5-1. 一个简单的方法: OneMethod.cs
 1using System;
 2class OneMethod
 3{
 4    public static void Main()
 5    {
 6        string myChoice;
 7        OneMethod om = new OneMethod();
 8
 9        do
10        {
11            myChoice = om.getChoice();
12            // Make a decision based on the user's choice
13            switch (myChoice)
14            {
15                case "A":
16                case "a":
17                    Console.WriteLine("You wish to add an address.");
18                    break;
19                case "D":
20                case "d":
21                    Console.WriteLine("You wish to delete an address.");
22                    break;
23                case "M":
24                case "m":
25                    Console.WriteLine("You wish to modify an address.");
26                    break;
27                case "V":
28                case "v":
29                    Console.WriteLine("You wish to view the address list.");
30                    break;
31                case "Q":
32                case "q":
33                    Console.WriteLine("Bye.");
34                    break;
35                default:
36                    Console.WriteLine("{0} is not a valid choice", myChoice);
37            }

38
39            // Pause to allow the user to see the results
40            Console.Write("Press any key to continue...");
41            Console.ReadLine();
42            Console.WriteLine();
43        }
 while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to quit
44    }

45
46    string getChoice()
47    {
48        string myChoice;
49        // Print A Menu
50        Console.WriteLine("My Address Book ");
51        Console.WriteLine("A - Add New Address");
52        Console.WriteLine("D - Delete Address");
53        Console.WriteLine("M - Modify Address");
54        Console.WriteLine("V - View Addresses");
55        Console.WriteLine("Q - Quit ");
56        Console.WriteLine("Choice (A,D,M,V,or Q): ");
57
58        // Retrieve the user's choice
59        myChoice = Console.ReadLine();
60        return myChoice;
61    }

62}


说明

1.清单5-1中的程序类似于第四课中的DoLoop程序。

区别在于:前一课中的程序打印出菜单内容,并在Main()方法中接受用户的输入,而本课中,该功能用一个名为getChoice()的方法实现,该方法的返回值类型是个字符串类型。在main方法中,在switch语句中用到了该串。方法"getChoice"实现了调用时所完成的工作。方法名后面的括号内是空的,因为调用getChoice()方法时,不需要传递任何数据。

 

3页 第1上一页123下一页
相关的教程: CSharp 入门
收藏此教程

当前平均分: 0.0(0 次打分)

-5-4-3-2-1012345
评论主题
您的大名
您的评论
验证码 点击换一个验证码
知识库搜索: