练习 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之间的数字后:

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

谢谢浏览!
    作者:音乐让我说(音乐让我说 - 博客园)
    
    出处:http://music.cnblogs.com/
    文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号