自由飞翔

导航

C#入门教程(下)

(4)foreach语句
    foreach语句是在C#中新引入的。它表示收集一个集合中的各元素,并针对各个元素执行内嵌语句。其格式为:
    foreach(type identifier in expression)embedded-statement
    其中类型(type)和标识符(identifier)用来声明循环变量,表达式(expression)对应集合。每执行一次内嵌语句,循环变量就依次取集合中的一个元素代入其中。在这里,循环变量只是一个只读型局部变量,如果试图改变它的值或将它作为一个ref或out类型的参数传递时,都将引发编译出错。
    Foreach语句中的expression必须是集合类型,如果该集合的元素类型与循环变量类型不一样,则必须有一个显示定义的从集合中的元素类型到循环变量元素类型的显示转换。
    下面的程序代码说明用一个foreach语句来循环显示列表中的元素。
    Using System;
    using System.Collections;
    class Tese
    {
    static void WriteList(Arraylist list){
    foreach(object o in list)
    Console.WriteLine(o);
    }
    static void Main(){
    ArrayList list=new ArrayList();
    for(int I=0; I<10; I++)
    list.Add(I);
    WriteList(list);
    }
    }
    3.转子语句
    (1)break语句和continue语句
    break语句用来退出最近的switch、while、do、for、foreach语句的循环,而continue语句用来开始一个新的while、do、for和foreach语句的循环。
    (2)标签声明和goto声明
    标签声明可以交替声明,goto声明可以把控制传送到标签声明。
    (3)return语句
    return语句返回对语句中的成员控制。无表达式的return语句只能在无返回值的成员中应用。带表达式的return语句只能在返回表达式的函数成员中运用。
    (4)throw语句与try语句
    throw语句用来抛出异常。Try语句提供一个在程序块执行过程中捕获异常的机制。此外,try语句还提供当try语句脱离控制时总是要执行的代码块。
    (五)异常处理
    程序中对异常的处理能使你的程序更加强壮。现在的许多程序设计语言都增加了异常处理的能力,C#也不例外。
    1.异常处理语句
    C#中的异常处理语句有三种形式:try-catch 捕捉异常、try-finally 清除异常、try-catch-finally 处理所有异常。
    下面的一段代码处理溢出异常:
    try{
    for(;n<=max;n++)
    sum*=n;
    }
    catch(OverfolwException oe)
    {
    Console.WriteLine(“溢出“);
    return;
    }
    2.清除异常
    try-finally 结构将清除异常。看下面的代码:
    try{
    for(;n<=max;n++)
    sum*=n;
    }
    finally
    {
    Console.WriteLine(“溢出“);
    return;
    }
    上面的代码中finally 子句中的代码在任何情况下总会被执行,即使没有异常发生。
    3.处理所有异常
    try-catch-finally 处理所有的异常。如下面的代码:
    try{
    for(;n<=max;n++)
    sum*=n;
    }
    catch(OverfolwException oe)
    {
    Console.WriteLine(“溢出“);
    return;
    }
    catch(Exception e)
    {
    //捕捉所有异常
    }
    finally
    {
    }
    4.抛出异常
    程序中我们可以先抛出异常,然后进行捕捉。
    抛出异常的语法如下:
    throw new Exception()
    四、一个简单的客户应用程序
    有了上面的基础,通过下面的实例可以轻松掌握如何创建组件和一个简单的客户应用程序。
    1.构建组件
    首先在文本编器中编写源代码,以下是两个文件add.cs,mult.cs的程序代码。
    //add.cs
    using System;
    public class AddClass
    {
    public static long Add(long I,long j)
    {
    return(I+j);
    }
    }
   
    //mult.cs
    using System;
    public class MultiplyClass
    {
    public static long Multiply(long x,long y)
    {
    return(x*y);
    }
    }
    以上代码定义了两个类AddClass和MultipyClass,并分别构造了两个方法Add()和Multiply()。
    2.编译组件
    csc/target:library/out:MyLibrary.dll Add.cs Mult.cs
    通过csc把Add.cs和Mult.cs两个文件编译成类型库MyLibrary.dll。
    3.客户应用程序调用
    客户应用程序调用组件的方法如下:
    //MyClient.cs
    using System;
    class MyClient
    {
    public static void Main(string[ ] args)
    {
    Console.WriteLine("Calling methods from MyLibrary.dll:");
    if (args.Length !=2)
    {
    Console.WriteLine("Usage:MyClient ");
    return;
    }
    long num1=long.Parse(args[0]);
    long num2=long.Parse(args[1]);
    long sum=AddClass.Add(num1,num2);
    long product=MultiplyClass.Multiply(num1,num2);
    Console.WriteLine("The sum of {0} and {1} is {2}",num1,num2,sum);
    Console.WriteLine("The product of {0} and {1} is {2}",num1,num2,product);
    }
    }
    在编译客户应用程序时,引用了上面编译好的新组件库MyLibrary.dll,然后运行MyClient.exe文件得到结果。
    Csc/out:MyClient.exe/reference:MyLibrary.dll MyClient.cs
    4.执行结果
    在命令行输入:
    >MyClient 2 3 (回车)
    5.输出结果
    Calling methods from MyLibrary.dll:
    The sum of 2 and 3 is 5
    The product of 2 and 3 is 6
    以上的组件并没有使用名字空间,如果构建组件的文件中添加了名字空间的语句,如下:
    using System;
    namespace MyMethods
    {
    public class …
    {
    public static long …(long I, long j)
    {
    …
    }
    }
    }
    那么,在客户应用程序中将使用引导名字空间的语句,这样程序才会根据名字空间的方向找到应用的类和方法。例如:
    //MyClient.cs
    using System;
    using MyMethods;
    class MyClient
    {
    …
    }
    以上名字空间的好处在于一个空间定义多个类或是名字空间再包括其他名字空间,这样可以降低编译程序的出错率。
   
    五、一个GUI例子
    该例子中有一个文本框,两个按钮,单击“点击我”的按钮在文本框中显示“你好,电脑报”。单击“终结者”的按钮结束程序。
    Using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
   
    namespace WindowsApplication1
    {
    ///
    /// Summary description for Form1.
    ///

    public class Form1 : System.Windows.Forms.Form
    {
    private System.Windows.Forms.TextBox textBox1;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    ///
    /// Required designer variable.
    ///

    private System.ComponentModel.Container components = null;
   
    public Form1()
    {
    //
    // Required for Windows Form Designer support
    //
    InitializeComponent(); //初始化窗体及子控件
   
    //
    // TODO: Add any constructor code after InitializeComponent call
    //
    }
   
    ///
    /// Clean up any resources being used.
    ///

    protected override void Dispose( bool disposing ) //释放对组件的引用,以便垃
    { //圾回收器回收无用的内存
    if( disposing )
    {
    if (components != null)
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    }
   
    #region Windows Form Designer generated code
    ///
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    ///

    private void InitializeComponent()
    {
    this.textBox1 = new System.Windows.Forms.TextBox();
    this.button1 = new System.Windows.Forms.Button();
    this.button2 = new System.Windows.Forms.Button();
    this.SuspendLayout();
    //
    // textBox1
    //
    this.textBox1.Location = new System.Drawing.Point(74, 64);
    this.textBox1.Name = "textBox1";
    this.textBox1.Size = new System.Drawing.Size(144, 21);
    this.textBox1.TabIndex = 0;
    this.textBox1.Text = "C#酷吗?";
    //
    // button1
    //
    this.button1.Location = new System.Drawing.Point(58, 160);
    this.button1.Name = "button1";
    this.button1.Size = new System.Drawing.Size(72, 24);
    this.button1.TabIndex = 1;
    this.button1.Text = "点击我";
    this.button1.Click += new System.EventHandler(this.button1OnClick);
    //
    // button2
    //
    this.button2.Location = new System.Drawing.Point(162, 160);
    this.button2.Name = "button2";
    this.button2.Size = new System.Drawing.Size(72, 24);
    this.button2.TabIndex = 2;
    this.button2.Text = "终结者";
    this.button2.Click += new System.EventHandler(this.button2OnClick);
    //
    // Form1
    //
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(292, 273);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
    this.button2,
    this.button1,
    this.textBox1});
    this.Name = "Form1";
    this.Text = "我爱C#";
    this.ResumeLayout(false);
   
    }
    #endregion
   
    ///
    /// The main entry point for the application.
    ///

    [STAThread]
    static void Main()
    {
    Application.Run(new Form1()); //启动程序
    }
    //响应单击按钮“点击我”的button1OnClick事件
    private void button1OnClick(object sender, System.EventArgs e)
    {
    textBox1.Text="你好!电脑报";
    //
    }
   
    //响应单击按钮“终结者”的button2OnClick事件
    private void button2OnClick(object sender, System.EventArgs e)
    {
    Application.Exit(); //退出应用程序
    }
    }
    } 

posted on 2006-05-10 17:23  李瑞  阅读(1039)  评论(0编辑  收藏  举报