代码改变世界

练习 C# 中的 goto

2011-10-05 11:53  音乐让我说  阅读(1145)  评论(0)    收藏  举报

说到 C# 中的 goto 关键字,微软是不建议使用的,因为一个项目中如果 goto 太多,会容易把代码搞得杂乱无章,下面是测试代码:

直接贴代码了:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConAppTest
{
    public class CSharp_Goto
    {
        public static void Test()
        {
            int x = 2, y = 4;
            int count = 0;
            string[,] array = new string[x, y]; // 申明一个 2 行 4 列的数组

            // 初始化数组
            for (int i = 0; i < x; i++)

                for (int j = 0; j < y; j++)
                    array[i, j] = (++count).ToString();

            // 读取输入
            Console.Write("请输入要查找的数(如果输入为空,则关闭系统):");

            // 请输入一个字符串
            string myNumber = Console.ReadLine();//读取一行字符串,回车即输入完毕
            if (string.IsNullOrEmpty(myNumber))
            {
                goto CloseSystem;
            }

            // 搜索
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    if (array[i, j].Equals(myNumber))
                    {
                        goto Found;
                    }
                }
            }

            Console.WriteLine("您输入的数字 {0} 没有找到!", myNumber);
            goto Finish;

        Found:
            Console.WriteLine("您输入的数字 {0} 已找到!", myNumber);

        Finish:
            Console.WriteLine("结束搜索");
            Console.ReadKey(); // 输入一个字符,即结束

        CloseSystem:
            Console.WriteLine("系统已经完毕!");
            Console.ReadKey();
        }
    }
}

  

下面是运行结果!

当不输入,直接回车时:

当输入一个1到8之间的数字后:

当随便输入一串字符串时:

谢谢浏览!