C# 编程练习汇总(要保持持续更新!)

验证控件常犯的一个错误

View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    用户名:

     
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="提交" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ErrorMessage="用户名不能为空!" ControlToValidate="TextBox1" Display="Dynamic" 
            ForeColor="#CC0000"></asp:RequiredFieldValidator>
            <asp:Button ID="Button2" runat="server"
                Text="Button2" />
       <%-- 如果页面中存在两个按钮,如果不设置“提交”按钮和RequiredFieldValidator控件的ViladationGroup
       属性为同一值的话,点击这两个按钮都会触发验证--%>
    </div>
    </form>
</body>
</html>

 

购物篮实现(就因为一个ListBox的SelectionMode属性就搞了半天,哎,汗颜)

<%--一定设置ListBox的SelectionMode属性为Multiple--%>

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
    <td align="center">预选商品</td>
    <td></td>
     <td align="center">购买商品</td>
    </tr>
    <tr>
    <td rowspan="4">
    <asp:ListBox ID="ListBox1" runat="server" Height="236px" Width="185px" 
            Font-Bold="True" Font-Size="Large" SelectionMode="Multiple"><%--一定设置ListBox的SelectionMode属性为Multiple--%>
    </asp:ListBox>
        </td>
    <td> 
    <asp:Button ID="Button1" runat="server" Text="购  买" onclick="Button1_Click" />
        </td>
     <td rowspan="4">
    <asp:ListBox ID="ListBox2" runat="server" Height="236px" Width="185px" 
             Font-Bold="True" Font-Size="Large" SelectionMode="Multiple">
    </asp:ListBox>
        </td>
    </tr>
    <tr>
    <td>
    <asp:Button ID="Button2" runat="server" Text="全购买" onclick="Button2_Click" />
        </td>
    </tr>
    <tr>
    <td>
    <asp:Button ID="Button3" runat="server" Text="退  回" onclick="Button3_Click" />
        </td>
    </tr>
    <tr>
    <td>
    <asp:Button ID="Button4" runat="server" Text="全退回" onclick="Button4_Click" />
        </td>
    </tr>
    </table>

    </div>
    </form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;



    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //向预选商品购物篮加载商品
                this.ListBox1.Items.Add("可口可乐");
                this.ListBox1.Items.Add("橙汁");
                this.ListBox1.Items.Add("签字笔");
                this.ListBox1.Items.Add("黄油");
                this.ListBox1.Items.Add("面包");
                this.ListBox1.Items.Add("馒头");
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (ListBox1.SelectedItem != null)//选定商品
            {
                //向购买商品购物篮里添加商品
                ListBox2.Items.Add(ListBox1.SelectedItem);
                //从预选商品购物篮里删除商品
                ListBox1.Items.Remove(ListBox1.SelectedItem);
            }

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            foreach (ListItem item in ListBox1.Items)//循环预选商品购物篮
            {
                this.ListBox2.Items.Add(item);//把每项商品都添加到购买商品购物篮里
            }
            this.ListBox1.Items.Clear();//删除预选商品购物篮里的商品

        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            if (this.ListBox2.SelectedItem != null)//选定商品
            {
                this.ListBox1.Items.Add(this.ListBox2.SelectedItem);//退回商品
                this.ListBox2.Items.Remove(this.ListBox2.SelectedItem);//删除商品
            }

        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            foreach (ListItem item in ListBox2.Items)//
            {
                this.ListBox1.Items.Add(item);//
            }
            this.ListBox2.Items.Clear();//

        }
    }

直接数据访问

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;//必须引入此命名空间

namespace Test
{


    class Program
    {
        static void Main(string[] args)
        {
            string connectionstring = "Data Source=ZKX-PC\\SQLEXPRESS;Initial Catalog=db_Student;User ID=sa;Password=123456";
            //Data Source=ZKX-PC\\SQLEXPRESS;要注意转义字符
            SqlConnection con = new SqlConnection(connectionstring);
            string sqlstring = "select * from tb_StuInfo  where stuID=1002";
            SqlCommand cmd = new SqlCommand(sqlstring, con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            Console.WriteLine("序号:{0} ", reader["stuID"]);
            Console.WriteLine("姓名:{0} ", reader["stuName"]);
            Console.WriteLine("性别:{0} ", reader["stuSex"]);
            Console.WriteLine("兴趣:{0} ", reader["stuHobby"]);
        }
    }
}

 

定义一个SortList对象,对该对象执行遍历、添加和删除操作

View Code
class Program
    {
        static void Main(string[] args)
        {
            SortedList sl = new SortedList();
            sl.Add(1,"11");
            sl.Add(2, "22");
            sl.Add(3, "33");
            sl.Add(4, "44");
            sl.Add(5, "55");

            Console.WriteLine("初始化后:");
            foreach (DictionaryEntry i in sl)//
            {
                Console.Write("Key:" + i.Key + " Value:" + i.Value + "\n");
            }
            Console.WriteLine();
            Console.WriteLine();

            sl.Remove(1);
            Console.WriteLine("使用sl.Remove(1);删除后:");
            foreach (DictionaryEntry i in sl)//
            {
                Console.Write("Key:" + i.Key + " Value:" + i.Value + "\n");
            }
            Console.WriteLine();
            Console.WriteLine();

            sl.RemoveAt(1);
            Console.WriteLine("使用sl.RemoveAt(1)删除后:");
            foreach (DictionaryEntry i in sl)//
            {
                Console.Write("Key:" + i.Key + " Value:" + i.Value + "\n");
            }
            Console.WriteLine();
            Console.WriteLine();

            sl.RemoveAt(1);
            Console.WriteLine("再次使用sl.RemoveAt(1)删除后:");
            foreach (DictionaryEntry i in sl)//
            {
                Console.Write("Key:" + i.Key + " Value:" + i.Value + "\n");
            }
            Console.WriteLine();
            Console.WriteLine();

            //sl.Remove("33");错误!!
            //Console.WriteLine("使用sl.Remove('33')删除后:");
            //foreach (DictionaryEntry i in sl)//
            //{
            //    Console.Write("Key:" + i.Key + " Value:" + i.Value + "\n");
            //}
            //Console.WriteLine();
            //Console.WriteLine();
        }
    }

 

定义一个Hashtable对象,对该对象执行遍历、添加和删除操作

View Code
class Program
    {
        static void Main(string[] args)
        {
            Hashtable hs = new Hashtable();
            hs.Add(1, "值1");
            hs.Add(2, "值2");
            hs.Add(3, "值3");
            hs.Add(4, "值4");
            hs.Add(5, "值5");

            Console.WriteLine("初始化后");
            foreach (DictionaryEntry i in hs)
            {
                Console.Write("Key:" + i.Key + " Value:" + i.Value + " \n");
            }
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("删除键2后");
            hs.Remove(2); //hs.Remove("值1");没有效果
            foreach (DictionaryEntry i in hs)//
            {
                Console.Write("Key:" + i.Key + " Value:" + i.Value + "\n");
            }
            Console.WriteLine();
            Console.WriteLine();
        }
    }

 

定义一个Queue对象,对该对象执行遍历、出队、和入队操作

View Code
class Program
    {    
        static void Main(string[] args)
        {
            Queue queue = new Queue();
            queue.Enqueue("第一个元素");
            queue.Enqueue("第二个元素");
            queue.Enqueue("第三个元素");
            queue.Enqueue("第四个元素");
            queue.Enqueue("第五个元素");

            Console.WriteLine("队列初始化后:");
            foreach (var i in queue)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("第六个元素入队后");
            queue.Enqueue("第六个元素");
            foreach (var i in queue)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.WriteLine();


            Console.WriteLine("第一个元素出队后");
            queue.Dequeue();
            foreach (var i in queue)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.WriteLine();


        }
    }

 

定义一个ArrayList对象,对该对象执行遍历、添加、插入、排序、和删除操作

View Code
class Program//要注意包含所需的命名空间Sestem.Collections
    {    
        static void Main(string[] args)
        {
            ArrayList arraylist = new ArrayList();
            arraylist.Add("a1");
            arraylist.Add("a2");
            arraylist.Add("a3");
            arraylist.Add("a4");
            arraylist.Add("a5");
            Console.WriteLine("赋值后:");
            foreach (var i in arraylist)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();

            arraylist.Insert(2, "a6");
            Console.WriteLine("插入后后:");
            foreach (var i in arraylist)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();

            arraylist.Remove("a2");
            Console.WriteLine("删除a2后:");
            foreach (var i in arraylist)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();

            arraylist.Sort();
            Console.WriteLine("重新排序后");
            foreach (var i in arraylist)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
        }
    }

 

定义一个数组,对该数组执行遍历、排序和搜索操作

View Code
 class Program//自己写的
    {
        static void SimpleSort(int[] arry)//冒泡排序
        {
            for (int i = 1; i < arry.Length; i++)
            {
                for (int j = 1; j <=arry.Length-i; j++)
                {
                    if (arry[j - 1] > arry[j])
                    {
                        int temp = arry[j - 1];
                        arry[j - 1] = arry[j];
                        arry[j] = temp;
                    }
                }
            }
            

        }
        static void Show(int[] a)//遍历数组进行输出
        {
            foreach (int i in a)
            {
                Console.Write(i+" ");
            }
            Console.WriteLine("");
        }
        static int Find(int[] a)//搜索
        {
            Console.WriteLine("请输入要查找的数组元素");
            int input = Convert.ToInt32(Console.ReadLine());//必须是ReadLine不能是Read
            Console.WriteLine("您输入的是:"+input);
            for (int i=0;i<a.Length;i++)
            {
                if (a[i] == input)
                {
                    Console.WriteLine("您要查找的数在数组中的下标为:{0}",i);
                    return i;
                }
            }
            Console.WriteLine("数组中查无此数值");
            return -1;

        }
        static void Main(string[] args)
        {
            int[] a = { 0, 88, 8, 7, 45, 5, 4, 4, 9, 1, 0, -1 };
            Show(a);
            Find(a);
            Console.WriteLine("排序后:");
            SimpleSort(a);
            Show(a);
            
        }
    }
View Code
class Program//借鉴的
    {
        static void Main(string[] args)
        {
            int[] arr = new int[] { 564, -98, 34, 67, 38, 50, 354, 213 };
            Console.WriteLine("排序前:");
            foreach (int i in arr)
            {
                System.Console.Write("{0} ", i);
            }
            Console.WriteLine("");
            Console.WriteLine("排序后:");
            Array.Sort(arr);//调用方法Sort进行排序
            foreach (int i in arr)
            {
                System.Console.Write("{0} ", i);
            }
            Console.WriteLine("");
            Console.WriteLine("反转数组顺序:");
            Array.Reverse(arr);//调用方法Reverse反转数组顺序
            foreach (int i in arr)
            {
                System.Console.Write("{0} ", i);
            }
            Console.WriteLine("使用方法BinarySearch搜索数组");
            Console.WriteLine("{0}在数组arr中的序号是:{1}", 678, Array.BinarySearch(arr, 678));
            Console.WriteLine("使用方法Find搜索数组");
            Console.WriteLine("数组arr中满足搜索条件的第一项是:{0}", Array.Find(arr, FindContion));
            Console.WriteLine("使用方法FindAll搜索数组");
            Console.Write("数组arr中满足搜索条件的所有项是:");
            int[] findAll = Array.FindAll(arr, FindContion);
            foreach (int i in findAll)
            {
                System.Console.Write("{0} ", i);
            }
            Console.WriteLine(" ");
            Console.WriteLine("使用方法FindLast搜索数组");
            Console.WriteLine("数组arr中满足搜索条件的最后一项是:{0}", Array.FindLast(arr, FindContion));
            Console.WriteLine("使用方法IndexOf搜索数组");
            Console.WriteLine("{0}在数组arr中的序号是:{1}", 34, Array.IndexOf(arr, 34));
            Console.WriteLine("使用方法LastIndexOf搜索数组");
            Console.WriteLine("{0}在数组arr中的序号是:{1}", 34, Array.LastIndexOf(arr, 34));
            Console.ReadLine();
        }
        //方法Find、FindAll和FindLast的搜索条件
        private static bool FindContion(int num)
        {
            if (num > 100)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

    }

 

TryParse 模式——对于可能在常见方案中引发异常的成员,可以考虑使用TryParse 模式来避免与异常相关的性能问题。我们将提供TryParse方法的这种行为叫做类型提供TryParse模式。TryParse模式为类型提供两个方法,假设第一个方法声明为Do,第二个方法则声明为TryDo。Do方法在执行过程中如果发生错误则引发异常,而TryDo方法会返回一个boolean值,方法执行失败返回false。如果要从TryDo中获取实际的返回值,则应该为方法提供out参数。不过,我们并不建议为所有的类型都提供TryParse模式,只有在考虑到Do方法会带来明显的性能损耗时,才建议使用TryParse。

View Code
 1 double re;  
 2 long ticks;  
 3  
 4 Stopwatch sw = Stopwatch.StartNew();  
 5 for (int i = 1; i < 1000; i++)  
 6 {  
 7     try  
 8     {  
 9         re = double.Parse("123");  
10     }  
11     catch  
12     {  
13         re = 0;  
14     }  
15 }  
16 sw.Stop();  
17 ticks = sw.ElapsedTicks;  
18 Console.WriteLine("double.Parse() 成功,{0} ticks", ticks);  
19  
20 sw = Stopwatch.StartNew();  
21 for (int i = 1; i < 1000; i++)  
22 {  
23     if (double.TryParse("123", out re) == false)  
24     {  
25         re = 0;  
26     }  
27 }  
28 sw.Stop();  
29 ticks = sw.ElapsedTicks;  
30 Console.WriteLine("double.TryParse() 成功,{0} ticks", ticks);  
31  
32 sw = Stopwatch.StartNew();  
33 for (int i = 1; i < 1000; i++)  
34 {  
35     try  
36     {  
37         re = double.Parse("aaa");  
38     }  
39     catch  
40     {  
41         re = 0;  
42     }  
43 }  
44 sw.Stop();  
45 ticks = sw.ElapsedTicks;  
46 Console.WriteLine("double.Parse() 失败,{0} ticks", ticks);  
47  
48 sw = Stopwatch.StartNew();  
49 for (int i = 1; i < 1000; i++)  
50 {  
51     if (double.TryParse("aaa", out re) == false)  
52     {  
53         re = 0;  
54     }  
55 }  
56 sw.Stop();  
57 ticks = sw.ElapsedTicks;  
58 Console.WriteLine("double.TryParse() 失败,{0} ticks", ticks); 

以上这段代码的输出为:

  1. double.Parse() 成功,6661 ticks  
  2. double.TryParse() 成功,2886 ticks  
  3. double.Parse() 失败,2062347 ticks  
  4. double.TryParse() 失败,3379 ticks 

可见, Parse和TryParse方法如果执行成功,它们的效率在一个数量级上,甚至在本示例中(在一个循环内),TryParse所带来的效率比Parse还要高一些。但若执行失败,Parse的执行效率相比于TryParse就太低了。

TryParse 方法类似于 Parse 方法,不同之处在于 TryParse 方法在转换失败时不引发异常。

View Code
 1 //Parse方法
 2 public void Do()
 3 {
 4     string s = “a”;
 5     double d;
 6     try
 7     {
 8         d = Double.Parse(s);
 9     }
10     catch (Exception ex)
11     {
12         d = 0;
13     }
14 }
15  
16 //TryParse方法
17 public void TryDo()
18 {
19     string s = "a";
20     double d;
21     if (double.TryParse(s, out d) == false)
22     {
23         d = 0;
24     }
25 }

ReadKey()是读到任意键为止,ReadLine()是读到一个回车为止。C#结尾的Console.Readkey()的作用:等待键盘输入,退出程序。使调试时能看到输出结果。如果没有此句,命令窗口会一闪而过。

View Code
 1 class Program
 2     {
 3         private List<Student> allStu = new List<Student>();
 4         string yesORno;
 5         bool flag = true;
 6        
 7         public void AddStudent()
 8         {
 9             while (flag)
10             {
11                 Student s = new Student();
12                 Console.WriteLine("请输入学生姓名:");
13                 s.StuName = Console.ReadLine();
14                 Console.WriteLine("请输入学生学号");
15                 s.StuNum = Console.ReadLine();
16                 allStu.Add(s);
17                
18                 Console.WriteLine("是否继续输入:请输入y或者n");
19                yesORno = Console.ReadKey().Key.ToString();
20                
21                 switch (yesORno)
22                 {
23                     case "Y":
24                         flag = true;
25                         break;
26                     case "N":
27                         flag = false;
28                         break;
29                 }
30             }
31         }
32         public void ShowStu()
33         {
34             for (int i = 0; i < allStu.Count; i++)
35             {
36                 Console.WriteLine(allStu[i].ToString());
37             }
38         }
39         static void Main(string[] args)
40         {
41             Program p = new Program();
42             p.AddStudent();
43             p.ShowStu();
44             Console.ReadLine();
45         }
46     }
47  
48 class Student
49     {
50         private string stuName;
51         public string StuName
52         {
53             get { return stuName; }
54             set { stuName = value; }
55         }
56         private string stuNum;
57         public string StuNum
58         {
59             get { return stuNum; }
60             set { stuNum = value; }
61         }
62         public override string ToString()
63         {
64             return "姓名" + stuName + "......." + "学号" + stuNum;
65         }
66     }

引发一个异常,并利用异常类的属性把异常的信息打印在屏幕上

View Code
 1 class Program
 2     {
 3         
 4         static void Main(string[] args)
 5         {
 6             int[] array = new int[100];
 7             try
 8             {
 9                 array[100] = 0;
10             }
11             catch(Exception e)
12             {
13                 Console.WriteLine("InnerException--" + e.InnerException);
14                 Console.WriteLine("Message--" + e.Message);
15                 Console.WriteLine("Source--" + e.Source);
16                 Console.WriteLine("StackTrace--" + e.StackTrace);
17                 Console.WriteLine("TargetSite--" + e.TargetSite);              
18 
19             }
20 
21         }
22     }

打印500以内的鲜花数,所谓鲜花数就是指一个三位数,其各个位的数的立方和等于该数本身。(设计一个方法,无返回值,按值传递次数为500)

View Code
posted @ 2012-11-07 23:37  .NET~莫愁  阅读(632)  评论(0编辑  收藏  举报