C#NET程序设计教程实验指导(清华大学江红,余青松)实验源码第七章


7.8

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

namespace c7._8
{
    class Account {
        private Object thisLock = new Object();
        int balance;
        Random r = new Random();
        public Account(int i)
        {
            balance = i;
        }
        int Withdraw(int amount)
        {
            if (balance < 0)
            {
                throw new Exception("账户余额不足(<=0)");
            }
            lock (thisLock)//同步锁
            {
                if (balance >= amount)
                {
                    Console.WriteLine("{0}  正在工作", Thread.CurrentThread.Name);
                    Console.WriteLine("提取前账户总额:{0}", balance);
                    Console.WriteLine("取款额:{0}", amount);
                    balance -= amount;
                    Console.WriteLine("提取后账户总额:{0}", balance);
                    Console.WriteLine();
                    return amount;//返回干嘛?
                }
                else
                {
                    /*
                    Console.WriteLine("{0}  正在工作", Thread.CurrentThread.Name);
                    Console.WriteLine("提取前账户总额:{0}", balance);
                    Console.WriteLine("取款额:{0},操作已被拒绝", amount);
                    Console.WriteLine();
                     */
                    return 0;//提款是否成功?
                }
            
            }
        }
        public void DoTransactions()
        {
            for (int i = 0; i < 100; i++)
                Withdraw(r.Next(1, 100));
        }
    
    }


    class Program
    {
        static void Main(string[] args)
        {
            Thread[] thread = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions));
                t.Name = "线程" + i;
                thread[i] = t;
            }
            for (int i = 0; i < 10; i++)
                thread[i].Start();
            Console.ReadLine();
        }
    }
}

 

 

7.7

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

namespace c7._7
{
    public class Worker
    {
        public void DoWork()
        {
            while (!shouldStop)
            {
                Console.WriteLine("工作线程.....");
            }
            Console.WriteLine("工作线程已经停止");
        }
        public void Stop()
        {
            shouldStop = true;
        }
        //volatile
        private volatile bool shouldStop;
    }


    class Program
    {
        static void Main(string[] args)
        {
            Worker wOject = new Worker();
            Thread wThread = new Thread(wOject.DoWork);

            wThread.Start();

            while (!wThread.IsAlive) //未激活工作线程前,一直循环
                ;//这里有空语句
            Thread.Sleep(1);

            wOject.Stop();
            wThread.Join();
            Console.WriteLine("主线程:Worker thread has terminal.");
            Console.ReadLine();


        }
    }
}

 

7.6

#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace c7._6
{
    [System.AttributeUsage(System.AttributeTargets.Class |
        System.AttributeTargets.Struct,
        AllowMultiple = true)
    ]
    public class Author : System.Attribute
    { 
        string name;
        public double version;
        public Author(string name)
        {
        this.name=name;
        version=1.00;
        }
        public string GetName()
        {
            return name;
        }
       

    }

    [Author("H.Ackerman")]//,Author("M.Knott",version=2.00)]
    class FirstClass { 
    
    }
    class SecondClass { 
    
    }

    [Author("H.Ackerman"), Author("M.Knott", version = 2.00)]
    class ThirdClass { 
        
    }
    
    class Program
    {
        static void Main()
        {
            printAuthorInfo(typeof(FirstClass));
            printAuthorInfo(typeof(SecondClass));
            printAuthorInfo(typeof(ThirdClass));
            System.Console.ReadLine();
        
        }
    //这就是传说中的反射? 
    private static void printAuthorInfo(System.Type t)
    {
        System.Console.WriteLine("作者的信息:{0}",t);
        System.Attribute []attrs=System.Attribute.GetCustomAttributes(t);
        foreach(System.Attribute attr in attrs)
        {
            if(attr is Author)
            {
                Author a=(Author)attr;
                System.Console.WriteLine("    {0},版本{1:f}",a.GetName(),a.version);
            }

        }
        System.Console.ReadLine();

 	
    }
    }
}

 

7.5

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

namespace c7._5
{
    public class Trace
    {
        [Conditional("DEBUG")]
        public static void Msg(string msg)
        {
            Console.WriteLine(msg);
        }
        [Conditional("DEBGU"),Conditional("TRACE")]
        public static void Method2()
        {
            Console.WriteLine("DEBUG or TRACE is defined");
        }
    
    }

    class Program
    {
        static void Main(string[] args)
        {
            Trace.Msg("Now in main...");
            Trace.Method2();
            Console.WriteLine("Main done!");
            Console.ReadKey();

        }
    }
}

 

 

7.4

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


namespace c7._4
{
    public class GenericList<T> : System.Collections.Generic.IEnumerable<T>
    {
        protected Node head;
        protected Node current = null;
        protected class Node
        {
            public Node next;
            private T data;
            public Node(T t)
            {
                next = null;
                data = t;
            }
            public Node Next
            {
                get { return next; }
                set { next = value; }
            }
            public T Data
            {
                set { data = value; }
                get { return data; }
            }

        }
        public GenericList()
        {
            head = null;
        }
        //implement 
        public System.Collections.Generic.IEnumerator<T> GetEnumerator()
        {
            Node current = head;
            while (current != null)
            {
                yield return current.Data;
                current = current.Next;
            }
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void AddHead(T t)
        {
            Node n = new Node(t);
            n.Next = head;
            head = n;
        }
    }

    //sort
    public class SortedList<T> : GenericList<T> where T : System.IComparable<T>
    {
        public void AddHead(T t)//书本居然漏写了,坑啊
        {
            Node tmp = new Node(t);
            tmp.next = head;
            head = tmp;
        }

        public void BubbleSort()
        {
            if (null == head || null == head.Next)
            {
                return;
            }
            bool swapped;
            do
            {
                Node previous = null;
                Node current = head;
                swapped = false;
                while (current.Next != null)//最好用Next而不是next
                {
                    //交换两个值
                    if (current.Data.CompareTo(current.next.Data) > 0)
                    {
                        Node tmp = current.next;
                        current.next = current.next.next;
                        tmp.next = current;
                        if (previous == null)
                        {
                            head = tmp;
                        }
                        else
                        {
                            previous.next = tmp;
                        }
                        previous = tmp;
                        swapped = true;//只要进行了排序,就保证了下一次排序的进行
                        //即只要需要排序,就进行下一次排序
                    }
                    else
                    {
                        previous = current;
                        current = current.next;
                    }
                }

            } while (swapped);

        }
    }
    public class Person : System.IComparable<Person>
    {
        string name;
        int age;
        public Person(string n, int i)
        {
            name = n;
            age = i;
        }
        public int CompareTo(Person p)
        {
            return age - p.age;
        }
        public override string ToString()
        {
            return name + ":" + age;
            //return base.ToString();
        }
        public bool Equals(Person p)
        {
            return age == p.age;
        }
    }
    static class Program
    {


        static void Main()
        {
            SortedList<Person> list = new SortedList<Person>();
            string[] name = new string[]{
                        "陈A",
                        "陈B",
                        "刘C",
                        "李四",
                        "王五",
                        "光哥"
                    };
            int[] age = new int[] { 45, 19, 28, 23, 18, 79 };
            for (int x = 0; x < 6; x++)
            {
                list.AddHead(new Person(name[x], age[x]));
            }
            Console.WriteLine("原始数列:");
            foreach (Person p in list)
                Console.WriteLine(p.ToString() + " ");
            Console.WriteLine();
            list.BubbleSort();
            Console.WriteLine("排序后数列:");
            foreach (Person p in list)
                Console.WriteLine(p.ToString() + " ");

            Console.ReadLine();
            Console.ReadLine();

        }
    }
}

 

 

 

7.3

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

namespace c7._3
{
    //哎,感觉就好像是C++的加强版
    public class mQueue<T>
    {
        private class Node
        {
           
            public Node(T t)
            {
                next = null;
                data = t;
            }

            private Node next;
            public Node Next {
                get {
                    return next;
                }
                set {
                    next= value;
                }
            }

            private T data;
            public T Data {
                get { return data; }
                set { data = value; }
            }

           
        }
        private Node head;
        public mQueue()
            {
                head=null;
            }
        public void Add(T t)
        {
            Node n = new Node(t);
            n.Next = head;
            head = n;
        }
       public IEnumerator<T> GetEnumerator()//for foreach
        //public void  Display()
        {
            Node pos = head;
            while (pos != null)
            {
                yield return pos.Data;
                pos = pos.Next;          
            }
        
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            mQueue<int> list = new mQueue<int>();
            Console.WriteLine("0-9 十个数字组成堆栈");
            for (int x = 0; x < 10; x++)
                list.Add(x);
            Console.WriteLine("堆栈内容如下:");
            foreach (int i in list)
                Console.Write(i + "  ");
            Console.ReadKey();


        }
    }
}

 

 

7.2

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

namespace c7._2
{
    class Program
    {
        static void Swap<T>(ref T lhs, ref T rhs)
        {
            T temp;
            temp=lhs;
            lhs = rhs;
            rhs = temp;
           
        }

        static void Main(string[] args)
        {
            Console.Write("请输入整数1:");
            int a = int.Parse(Console.ReadLine());
            Console.Write("请输入整数2:");
            int b = int.Parse(Console.ReadLine());

            Console.WriteLine("原始值:a={0},b={1}", a, b);
            Swap<int>(ref a,ref b);
            Console.WriteLine("交换后:a={0},b={1}", a, b);

            Console.Write("请输入实数1:");
            double c = double.Parse(Console.ReadLine());
            Console.Write("请输入实数2:");
            double d = double.Parse(Console.ReadLine());

            Console.WriteLine("原始值:c={0},d={1}", c, d);
            Swap<double>(ref c, ref d);
            Console.WriteLine("交换后:c={0},d={1}", c, d);
            Console.ReadKey();


        }
    }
}

 

 

7.1

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

namespace c7._1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> arrInt = new List<int>{ 1, 3, 5 };
            List<string> arrStr = new List<string> { "one", "two", "three" };
            Console.WriteLine("整型数组如下:");
            foreach (int i in arrInt)
                Console.Write("{0,-5}", i);
            Console.WriteLine("\n整型字符数组如下:");
            foreach (string s in arrStr)
                Console.Write("{0,-5}", s);



            arrInt.Add(4);
            arrStr.Remove("one");
            Console.WriteLine("整型数组如下:");
            foreach (int i in arrInt)
                Console.Write("{0,-5}", i);
            Console.WriteLine("\n整型字符数组如下:");
            foreach (string s in arrStr)
                Console.Write("{0,-5}", s);

            Console.ReadKey();

——————————————————————————————————————————————————

//写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:https://www.royalchen.com/

author:royalchen

Email:royalchen@royalchen.com

———————————————————————————————————————————————————

 

 

 


发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注