Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)qq
published in(发表于) 2014/7/11 9:16:57
C#中goto语句的使用方法

C#中goto语句的使用方法

C#中goto语句的使用方法

goto语句属于无条件的跳转语句,因为C#允许在代码行加上标签,这样就可以用goto语句直接跳转到这些代码行上。该语句有其优缺点,优点在于可以方便地控制何时去执行指定代码;主要缺点在于过多地使用这个语句将很难读懂代码段。

示例

goto语句的使用

通过使用goto语句跳出嵌套循环完成数字的查找,程序代码如下:

using System;

public class GotoTest1

{

static void Main()

{

int x = 200, y = 4;

int count = 0;

string[,] array = new string[x, y];

for (int i = 0; i < x; i++)

for (int j = 0; j < y; j++)

array[i, j] = (++count).ToString();

Console.Write("输出结果为:n输入查找的数字:");

string myNumber = Console.ReadLine();

for (int i = 0; i < x; i++)

{

for (int j = 0; j < y; j++)

{

if (array[i, j].Equals(myNumber))

{

goto Found;

}

}

}

// http://www.isstudy.com

Console.WriteLine("数字{0} 无法找到.", myNumber);

goto Finish;

Found:

Console.WriteLine("数字{0} 存在.", myNumber);

Finish:

Console.WriteLine("结束查找.");

Console.Read();

}

}


键运行程序,运行结果如图1所示。



图1 goto语句

完整程序代码如下:

★★★★★主程序文件完整程序代码★★★★★

using System;

using System.Collections.Generic;

using System.Text;

namespace _3_13

{

class Program

{

static void Main()

{

int x = 200, y = 4;

int count = 0;

string[,] array = new string[x, y];

for (int i = 0; i < x; i++)

for (int j = 0; j < y; j++)

array[i, j] = (++count).ToString();

Console.Write("输出结果为:n输入查找的数字:");

string myNumber = Console.ReadLine();

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);

// http://www.isstudy.com

goto Finish;

Found:

Console.WriteLine("数字{0} 存在.", myNumber);

Finish:

Console.WriteLine("结束查找.");

Console.Read();

}

}

}




If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759