C#学习补充一

1.out参数
2.ref参数
3.params可变参数
4.方法的重载(函数名称相同,返回类型不一样)
5.静态和非静态的区别
6.计时器
7.字符串的方法
8.new 关键字(子类可以重写父类的方法)
9.里氏转换原则以及is和as的用法
10.ArrayList集合以及其方法
11.ToString的问题
12.键值对集合
13.var数据类型
14.File类
15.使用File类操作文件的数据
16.List泛型集合
17.装箱和拆箱
18.Dictionary
19.文件流
20.使用文件流来实现多媒体文件的复制
21.StreamReader读取文件、StreamWriter写入文件
22、实现多态的3种手段:1、虚方法 2、抽象类 3、接口
23、序列化与反序列化
24.部分类

25.密封类(密封类无法被继承)

26.重写ToString__方法
27.接口

28.自动属性和普通属性

29.显示实现接口
30.GUID产生一个不会重复的编号
31.Directory文件夹目录
32.进程
33.线程
34.MD5加密
35.使用GDI绘制简单的图形
36.使用GDI绘制验证码
 37.创建XML
 38.创建带属性的XML文档
 39.追加XML
 40.读取XML文档
 41.委托(将方法作为参数传递给方法)
 42.匿名函数和lamda表达式
 43.泛型委托
 44.单例模式
 45.多播委托
 
 
 
 

1.out参数

class Program
    {
        static void Main(string[] args)
        {
            //写一个方法 求一个数组中的最大值、最小值、总和、平均值
            int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            ////将要返回的4个值,放到一个数组中返回

            //int[] res = GetMaxMinSumAvg(numbers);
            //Console.WriteLine("最大值是{0},最小值是{1},总和是{2},平均值是{3}", res[0], res[1], res[2], res[3]);
            //Console.ReadKey();
            int max1;
            int min1;
            int sum1;
            int avg1;
            bool b;
            string s;
            double d;
            Test(numbers, out max1, out min1, out sum1, out avg1, out b, out s, out d);

            Console.WriteLine(max1);
            Console.WriteLine(min1);
            Console.WriteLine(sum1);
            Console.WriteLine(avg1);
            Console.WriteLine(b);
            Console.WriteLine(s);
            Console.WriteLine(d);
            Console.ReadKey();

        }
        /// <summary>
        /// 计算一个数组的最大值、最小值、总和、平均值
        /// </summary>
        /// <param name="nums"></param>
        /// <returns></returns>
        public static int[] GetMaxMinSumAvg(int[] nums)
        {
            int[] res = new int[4];
            //假设 res[0] 最大值  res[1]最小值  res[2]总和  res[3]平均值
            res[0] = nums[0];//max
            res[1] = nums[0];//min
            res[2] = 0;//sum
            string name = "孙全";
            bool b = true;
            for (int i = 0; i < nums.Length; i++)
            {
                //如果当前循环到的元素比我假定的最大值还大 
                if (nums[i] > res[0])
                {
                    //将当前循环到的元素赋值给我的最大值
                    res[0] = nums[i];
                }
                if (nums[i] < res[1])
                {
                    res[1] = nums[i];
                }
                res[2] += nums[i];
            }
            //平均值
            res[3] = res[2] / nums.Length;
            return res;


        }


        /// <summary>
        /// 计算一个整数数组的最大值、最小值、平均值、总和
        /// </summary>
        /// <param name="nums">要求值得数组</param>
        /// <param name="max">多余返回的最大值</param>
        /// <param name="min">多余返回的最小值</param>
        /// <param name="sum">多余返回的总和</param>
        /// <param name="avg">多余返回的平均值</param>
        public static void Test(int[] nums, out int max, out int min, out int sum, out int avg, out bool b, out string s, out double d)
        {
            //out参数要求在方法的内部必须为其赋值
            max = nums[0];
            min = nums[0];
            sum = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] > max)
                {
                    max = nums[i];
                }
                if (nums[i] < min)
                {
                    min = nums[i];
                }
                sum += nums[i];
            }
            avg = sum / nums.Length;


            b = true;
            s = "123";
            d = 3.13;
        }

2.ref参数

static void Main(string[] args)
        {
            double salary = 5000;
            JiangJin(ref salary);
            Console.WriteLine(salary);
            Console.ReadKey();
        }

        public static void JiangJin(ref double s)
        {
            s += 500;

        }

3.params可变参数

static void Main(string[] args)
        {
            //   int[] s = { 99, 88, 77 };
            //Test("张三",99,100,100,100);
            //Console.ReadKey();

            //求任意长度数组的和 整数类型的
            int[] nums = { 1, 2, 3, 4, 5 };
            int sum = GetSum(8,9);
            Console.WriteLine(sum);
            Console.ReadKey();
        }

        public static int GetSum(params int[] n)
        {
            int sum = 0;
            for (int i = 0; i < n.Length; i++)
            {
                sum += n[i];
            }
            return sum;
        }


        public static void Test(string name, int id, params int[] score)
        {
            int sum = 0;

            for (int i = 0; i < score.Length; i++)
            {
                sum += score[i];
            }
            Console.WriteLine("{0}这次考试的总成绩是{1},学号是{2}", name, sum, id);
        }

4.方法的重载(函数名称相同,返回类型不一样)

public static void M(int n1, int n2)
        {
            int result = n1 + n2;
        }
        //public static int M(int a1, int a2)
        //{
        //    return a1 + a2;
        //}
        public static double M(double d1, double d2)
        {
            return d1 + d2;
        }
        public static void M(int n1, int n2, int n3)
        {
            int result = n1 + n2 + n3;
        }
        public static string M(string s1, string s2)
        {
            return s1 + s2;
        }

5.静态和非静态的区别

static void Main(string[] args)
        {
            //调用实例成员
            Person p = new Person();
            p.M1();//实例方法
            Person.M2();//静态方法
           // Student s = new Student();


            Console.WriteLine();
            Console.ReadKey();
        }

6.计时器

//创建了一个计时器,用来记录程序运行的时间
            //00:00:00.0422166
            Stopwatch sw = new Stopwatch();
            sw.Start();//开始计时
            for (int i = 0; i < 100000; i++)
            {
                //str += i;
                sb.Append(i);
            }
            sw.Stop();//结束计时

7.字符串的方法

//大小写转换
lessonTwo = lessonTwo.ToUpper();
lessonTwo = lessonTwo.ToLower();
//分割字符串Split
char[] chs = { ' ', '_', '+', '=', ',' };
string[] str = s.Split(chs,StringSplitOptions.RemoveEmptyEntries);
//判断包不包含指定字符串
string str = "国家关键人物老赵";
str.Contains("老赵");
//替换字符串
str = str.Replace("老赵", "**");
//Substring 截取字符串
string str = "今天天气好晴朗,处处好风光";
str = str.Substring(1,2);
str.EndsWith("");
int index = str.IndexOf('',2);
int index = str.LastIndexOf('');
string str = "            hahahah          ";
str = str.Trim();
str = str.TrimStart();
str = str.TrimEnd();
string.IsNullOrEmpty(str);

 8.new 关键字(子类可以重写父类的方法)

public class Person
    {
        private string _name;
        
        public void SayHello()
        {
            Console.WriteLine("大家好,我是人类");
        }
    }

public class Reporter : Person
    {
        public Reporter(string name, int age, char gender, string hobby)
            : base(name, age, gender)
       



        public new void SayHello()
        {
            Console.WriteLine("大家好,我是记者");
        }
    }

9.里氏转换原则以及is和as的用法

//1)、子类可以赋值给父类:如果有一个地方需要一个父类作为参数,我们可以给一个子类代替
 Person p = new Student();
//2)、如果父类中装的是子类对象,那么可以讲这个父类强转为子类对象。
            //is的用法
            //if (p is Student)
            //{
            //    Student ss = (Student)p;
            //    ss.StudentSayHello();
            //}
            //else
            //{
            //    Console.WriteLine("转换失败");
            //}

            //as的用法

            Student t = p as Student;

10.ArrayList集合以及其方法

            //创建了一个集合对象
            ArrayList list = new ArrayList();
            //集合:很多数据的一个集合
            //数组:长度不可变、类型单一
            //集合的好处:长度可以任意改变  类型随便
            list.Add(1);
            list.Add(3.14);
            list.Add(true);
            list.Add("张三");
            list.Add('');
            list.Add(5000m);
            list.Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
            Person p = new Person();
            list.Add(p);
            list.Add(list);
 //list.Clear();清空所有元素
            //list.Remove(true);删除单个元素 写谁就删谁
            //list.RemoveAt(0);根据下标去删除元素
            //list.RemoveRange(0, 3);根据下标去移除一定范围的元素
            // list.Sort();//升序排列
            //list.Reverse();反转
            //list.Insert(1, "插入的");在指定的位置插入一个元素
            //list.InsertRange(0, new string[] { "张三", "李四" });在指定的位置插入一个集合
            //bool b = list.Contains(1);判断是否包含某个指定的元素
            list.Add("颜世伟");
            if (!list.Contains("颜世伟"))
            {
                list.Add("颜世伟");
            }
Console.WriteLine(list.Count);
            Console.WriteLine(list.Capacity);
            Console.ReadKey();
            //count 表示这个集合中实际包含的元素的个数
            //capcity 表示这个集合中可以包含的元素的个数

11.ToString的问题

           //我们将一个对象输出到控制台  默认情况下 打印的就是这个对象所在的类的命名空间
            int[] nums = { 1, 2, 3, 4, 5 };
            Console.WriteLine(nums.ToString());
            Person p = new Person();
            Console.WriteLine(p.ToString());
            Console.ReadKey();

12.键值对集合

Hashtable ht = new Hashtable();
            ht.Add(1, "张三");
            ht.Add(2, true);
            ht.Add(3, '');
            ht.Add(false, "错误的");
            ht.Add(5, "张三");
            ht[6] = "新来的";//这也是一种添加数据的方式
            ht[1] = "把张三干掉";
            ht.Add("abc", "cba");

            //abc----cba
            if (!ht.ContainsKey("abc"))
            {
                //ht.Add("abc", "哈哈哈");
                ht["abc"] = "哈哈哈";
            }
            else
            {
                Console.WriteLine("已经包含abc这个键!!!");
            }


           // ht.Clear(); //移除集合中所有的元素
            ht.Remove(3);

            foreach (var item in ht.Keys)
            {
                Console.WriteLine("键是-----{0}==============值是{1}", item, ht[item]);
            }
            //在键值对集合中 是根据键去找值的
            //Console.WriteLine(ht[1]);
            //Console.WriteLine(ht[2]);
            //Console.WriteLine(ht[3]);
            //Console.WriteLine(ht[false]);
            //Console.WriteLine("==================================");
            //for (int i = 0; i < ht.Count; i++)
            //{
            //    Console.WriteLine(ht[i]);
            //}
            Console.ReadKey();

13.var数据类型

           //var:根据值能够推断出来类型
            //c#是一门强类型语言:在代码当中,必须对每一个变量的类型有一个明确的定义
            //var n = 15;
            //var n2 = "张三";
            //var n3 = 3.14;
            //var n4 = 5000m;
            //var n5 = true;
            //var n6 = '男';
            //Console.WriteLine(n.GetType());
            //Console.WriteLine(n2.GetType());
            //Console.WriteLine(n3.GetType());
            //Console.WriteLine(n4.GetType());
            //Console.WriteLine(n5.GetType());
            //Console.WriteLine(n6.GetType());

14.File类

//创建一个文件
            //File.Create(@"C:UsersSpringRainDesktop
ew.txt");
 //删除一个文件
            //File.Delete(@"C:UsersSpringRainDesktop
ew.txt");
//复制一个文件
            //File.Copy(@"C:UsersSpringRainDesktopcode.txt", @"C:UsersSpringRainDesktop
ew.txt");
//剪切
            File.Move(@"C:UsersSpringRainDesktopcode.txt", @"C:UsersSpringRainDesktop
ewnew.txt");

15.使用File类操作文件的数据

       //byte[] buffer = File.ReadAllBytes(@"C:UsersSpringRainDesktop1.txt");
       //
EncodingInfo[] en = Encoding.GetEncodings(); //foreach (var item in en) //{ // Console.WriteLine(item.DisplayName); //} //Console.ReadKey(); //将字节数组转换成字符串 //string s = Encoding.UTF8.GetString(buffer); //Console.WriteLine(s); // Console.WriteLine(buffer.ToString()); //编码格式:指的就是你以怎样的形式来存储字符串 //a-z 0-9 Ascii 117 u---->汉字--->GB2312 GBK //int n = (int)'u'; //char c = (char)188; //Console.WriteLine(c); ////Console.WriteLine(n); //string s="今天天气好晴朗,处处好风光"; ////将字符串转换成字节数组 //byte[] buffer= Encoding.Default.GetBytes(s); ////以字节的形式向计算机中写入文本文件 //File.WriteAllBytes(@"C:UsersSpringRainDesktop1.txt", buffer); //Console.WriteLine("写入成功"); //Console.ReadKey(); //使用File类来实现一个多媒体文件的复制操作 //读取 byte[] buffer = File.ReadAllBytes(@"C:UsersSpringRainDesktop12333.wmv"); Console.ReadKey(); ////写入 //File.WriteAllBytes(@"C:UsersSpringRainDesktop ew.wav", buffer); //Console.WriteLine("复制成功"); //Console.ReadKey(); //byte[] buffer=new byte[1024*1024*5]; //while (true) //{ // File.WriteAllBytes(@"C:UsersSpringRainDesktop123.wmv", buffer); //}

16.List泛型集合

            //创建泛型集合对象
            //List<int> list = new List<int>();
            //list.Add(1);
            //list.AddRange(new int[] { 1, 2, 3, 4, 5, 6 });
            //List泛型集合可以转换为数组
            //int[] nums = list.ToArray();
            //数组可以转换为 List泛型集合
           //char[] chs = new char[] { 'c', 'b', 'a' };
            //List<char> listChar = chs.ToList();

17.装箱和拆箱

            int n = 10;
            object o = n;//装箱
            int nn = (int)o;//拆箱

18.Dictionary

            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1, "张三");
            dic.Add(2, "李四");
            dic.Add(3, "王五");
            dic[1] = "新来的";
            foreach (KeyValuePair<int,string> kv in dic)
            {
                Console.WriteLine("{0}---{1}",kv.Key,kv.Value);
            }
            Console.ReadKey();

19.文件流

            //使用FileStream来读取数据
            FileStream fsRead = new FileStream(@"C:UsersSpringRainDesktop
ew.txt", FileMode.OpenOrCreate, FileAccess.Read);
            byte[] buffer = new byte[1024 * 1024 * 5];
            //3.8M  5M
            //返回本次实际读取到的有效字节数
            int r = fsRead.Read(buffer, 0, buffer.Length);
            //将字节数组中每一个元素按照指定的编码格式解码成字符串
            string s = Encoding.UTF8.GetString(buffer, 0, r);
            //关闭流
            fsRead.Close();
            //释放流所占用的资源
            fsRead.Dispose();
            Console.WriteLine(s);
            Console.ReadKey();

20.使用文件流来实现多媒体文件的复制

 static void Main(string[] args)
        {
            //思路:就是先将要复制的多媒体文件读取出来,然后再写入到你指定的位置
            string source = @"C:UsersSpringRainDesktop1、复习.wmv";
            string target = @"C:UsersSpringRainDesktop
ew.wmv";
            CopyFile(source, target);
            Console.WriteLine("复制成功");
            Console.ReadKey();
        }

        public static void CopyFile(string soucre, string target)
        {
            //1、我们创建一个负责读取的流
            using (FileStream fsRead = new FileStream(soucre, FileMode.Open, FileAccess.Read))
            {
                //2、创建一个负责写入的流
                using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    //因为文件可能会比较大,所以我们在读取的时候 应该通过一个循环去读取
                    while (true)
                    {
                        //返回本次读取实际读取到的字节数
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        //如果返回一个0,也就意味什么都没有读取到,读取完了
                        if (r == 0)
                        {
                            break;
                        }
                        fsWrite.Write(buffer, 0, r);
                    }

                 
                }
            }
        }

21.StreamReader读取文件、StreamWriter写入文件

            //使用StreamReader来读取一个文本文件
            //using (StreamReader sr = new StreamReader(@"C:UsersSpringRainDesktop抽象类特点.txt",Encoding.Default))
            //{
            //    while (!sr.EndOfStream)
            //    {
            //        Console.WriteLine(sr.ReadLine());
            //    }
            //}


            //使用StreamWriter来写入一个文本文件
            using (StreamWriter sw = new StreamWriter(@"C:UsersSpringRainDesktop
ewnew.txt",true))
            {
                sw.Write("看我有木有把你覆盖掉");
            }
            Console.WriteLine("OK");
            Console.ReadKey();
        }

22、实现多态的3种手段:1、虚方法 2、抽象类 3、接口

//虚方法
public
class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } public Person(string name) { this.Name = name; } public virtual void SayHello() { Console.WriteLine("我是人类"); } } public class Chinese : Person { public Chinese(string name) : base(name) { } public override void SayHello() { Console.WriteLine("我是中国人,我叫{0}", this.Name); } }
//抽象类
public abstract class Animal
    {

        public virtual void T()
        {
            Console.WriteLine("动物有声明");
        }

        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        public Animal(int age)
        {
            this.Age = age;
        }
        public abstract void Bark();
        public abstract string Name
        {
            get;
            set;
        }

     //   public abstract string TestString(string name);


        public Animal()
        { 
            
        }
   }


    public abstract class Test : Animal
    { 
        
    }

    public class Dog : Animal
    {
        public override void Bark()
        {
            Console.WriteLine("狗狗旺旺的叫");
        }

        public override string Name
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }public class Cat : Animal
    {
        public override void Bark()
        {
            Console.WriteLine("猫咪喵喵的叫");
        }

        public override string Name
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    }

23、序列化与反序列化

 //要将p这个对象 传输给对方电脑
            //Person p = new Person();
            //p.Name = "张三";
            //p.Age = 19;
            //p.Gender = '男';
            //using (FileStream fsWrite = new FileStream(@"C:UsersSpringRainDesktop111.txt", FileMode.OpenOrCreate, FileAccess.Write))
            //{ 
            //    //开始序列化对象
            //    BinaryFormatter bf = new BinaryFormatter();
            //    bf.Serialize(fsWrite, p);
            //}
            //Console.WriteLine("序列化成功");
            //Console.ReadKey();

            //接收对方发送过来的二进制 反序列化成对象
            Person p;
            using (FileStream fsRead = new FileStream(@"C:UsersSpringRainDesktop111.txt", FileMode.OpenOrCreate, FileAccess.Read))
            {
                BinaryFormatter bf = new BinaryFormatter();
                p = (Person)bf.Deserialize(fsRead);
            }
            Console.WriteLine(p.Name);
            Console.WriteLine(p.Age);
            Console.WriteLine(p.Gender);
            Console.ReadKey();

24.部分类

25.密封类(密封类无法被继承)

    public sealed class Person:Test
    { 
        
    }

26.重写ToString__方法

    static void Main(string[] args)
        {
            Person p = new Person();
            Console.WriteLine(p.ToString());
            Console.ReadKey();
        }
    }

    public class Person
    {
        public override string ToString()
        {
            return "Hello World";
        }
    }

27.接口

public interface IFlyable
    {
        //接口中的成员不允许添加访问修饰符 ,默认就是public
        void Fly();
        string Test();
        //不允许写具有方法体的函数
     //   string _name;
         string Name
        {
            get;
            set;
        }
    }

28.自动属性和普通属性

29.显示实现接口

class Program
    {
        static void Main(string[] args)
        {
            //显示实现接口就是为了解决方法的重名问题
            IFlyable fly = new Bird();
            fly.Fly();
            Bird bird = new Bird();
            bird.Fly();

            Console.ReadKey();
        }
    }


    public class Bird : IFlyable
    {
        public void Fly()
        {
            Console.WriteLine("鸟飞会");
        }
        /// <summary>
        /// 显示实现接口
        /// </summary>
         void IFlyable.Fly()
        {
            Console.WriteLine("我是接口的飞");
        }

    }

    public interface IFlyable
    {
        void Fly();
    }

30.GUID产生一个不会重复的编号

           //产生一个不会重复的编号
            Console.WriteLine(Guid.NewGuid().ToString());
            Console.WriteLine(Guid.NewGuid().ToString());
            Console.WriteLine(Guid.NewGuid().ToString());
            Console.WriteLine(Guid.NewGuid().ToString());
            Console.WriteLine(Guid.NewGuid().ToString());
            Console.ReadKey();

31.Directory文件夹目录

/File  Path   FileStream  StreamReader  StreamWriter
            //Directory 文件夹 目录
            //创建文件夹
            //Directory.CreateDirectory(@"C:a");
            //Console.WriteLine("创建成功");
            //Console.ReadKey();

            //删除文件夹
            //Directory.Delete(@"C:a",true);
            //Console.WriteLine("删除成功");
            //Console.ReadKey();


            //剪切文件夹
            //Directory.Move(@"c:a", @"C:UsersSpringRainDesktop
ew");
            //Console.WriteLine("剪切成功");
            //Console.ReadKey();


            //获得指定文件夹下所有文件的全路径
            //string[] path = Directory.GetFiles(@"C:UsersSpringRainDesktopPicture","*.jpg");
            //for (int i = 0; i < path.Length; i++)
            //{
            //    Console.WriteLine(path[i]);
            //}
            //Console.ReadKey();


            //获得指定目录下所有文件夹的全路径
            //string[] path = Directory.GetDirectories(@"C:UsersSpringRainDesktop
ew");
            //for (int i = 0; i < path.Length; i++)
            //{
            //    Console.WriteLine(path[i]);
            //}
            //Console.ReadKey();


            //判断指定的文件夹是否存在
            //if (Directory.Exists(@"C:a"))
            //{
            //    for (int i = 0; i < 100; i++)
            //    {
            //        Directory.CreateDirectory(@"C:a" + i);
            //    }   
            //}
            //Console.WriteLine("OK");
            //Console.ReadKey();


            //Directory.Delete(@"C:a", true);
            //Console.ReadKey();

32.进程

//获得当前程序中所有正在运行的进程
            //Process[] pros = Process.GetProcesses();
            //foreach (var item in pros)
            //{
            //    //不试的不是爷们
            //    //item.Kill();
            //    Console.WriteLine(item);
            //}

            //通过进程打开一些应用程序
            //Process.Start("calc");
            //Process.Start("mspaint");
            //Process.Start("notepad");
            //Process.Start("iexplore", "http://www.baidu.com");

            //通过一个进程打开指定的文件

            ProcessStartInfo psi = new ProcessStartInfo(@"C:UsersSpringRainDesktop1.exe");
           
            //第一:创建进程对象
            Process p = new Process();
            p.StartInfo = psi;
            p.Start();
           // p.star


            Console.ReadKey();

33.线程

34.MD5加密

public static string GetMD5(string str)
        {
            //创建MD5对象
            MD5 md5 = MD5.Create();
            //开始加密
            //需要将字符处转换成字节数组
            byte[] buffer = Encoding.GetEncoding("GBK").GetBytes(str);
            //返回一个加密好的字节数组
            byte[] MD5Buffer = md5.ComputeHash(buffer);

            //将字节数组转换成字符串
            //字节数组---字符串
            //将字节数组中每个元素按照指定的编码格式解析成字符串
            //直接将数组ToString();
            //将字节数组中的每个元素ToString()
          //  return Encoding.GetEncoding("GBK").GetString(MD5Buffer);

            // 189 273 345 我爱你
            // 189 273 345
            string strNew = "";
            for (int i = 0; i < MD5Buffer.Length; i++)
            {
                strNew += MD5Buffer[i].ToString("x2");
            }
            return strNew;
        }

35.使用GDI绘制简单的图形

            //创建GDI对象
            Graphics g = this.CreateGraphics();// new Graphics();
            //创建画笔对象
            Pen pen = new Pen(Brushes.Red);
            //创建两个点
            Point p1 = new Point(30, 50);
            Point p2 = new Point(250, 250);
            g.DrawLine(pen, p1, p2);

            Size size=new System.Drawing.Size(80,80);
            Rectangle rec=new Rectangle(new Point(50,50),size);
            g.DrawRectangle(pen,rec);

            Size size=new System.Drawing.Size(180,180);
            Rectangle rec=new Rectangle(new Point(150,150),size);
            g.DrawPie(pen, rec, 60, 60);


            g.DrawString("老赵是最帅的", new Font("宋体", 20, FontStyle.Underline), Brushes.Black, new Point(300, 300));

36.使用GDI绘制验证码

            Random r = new Random();
            string str = null;
            for (int i = 0; i < 5; i++)
            {
                int rNumber = r.Next(0, 10);
                str += rNumber;
            }
            //  MessageBox.Show(str);
            //创建GDI对象
            Bitmap bmp = new Bitmap(150, 40);
            Graphics g = Graphics.FromImage(bmp);

            for (int i = 0; i < 5; i++)
            {
                Point p = new Point(i * 20, 0);
                string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };
                Color[] colors = { Color.Yellow, Color.Blue, Color.Black, Color.Red, Color.Green };
                g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), p);
            }

            for (int i = 0; i < 20; i++)
            {
                Point p1=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
                Point p2=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
                g.DrawLine(new Pen(Brushes.Green), p1, p2);
            }

            for (int i = 0; i < 500; i++)
            {
                Point p=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
                bmp.SetPixel(p.X, p.Y, Color.Black);
            }


            //将图片镶嵌到PictureBox中
            pictureBox1.Image = bmp;

37.创建XML

            //通过代码来创建XML文档
            //1、引用命名空间
            using System.Xml;
            //2、创建XML文档对象
            XmlDocument doc = new XmlDocument();
            //3、创建第一个行描述信息,并且添加到doc文档中
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);
            //4、创建根节点
            XmlElement books = doc.CreateElement("Books");
            //将根节点添加到文档中
            doc.AppendChild(books);

            //5、给根节点Books创建子节点
            XmlElement book1 = doc.CreateElement("Book");
            //将book添加到根节点
            books.AppendChild(book1);


            //6、给Book1添加子节点
            XmlElement name1 = doc.CreateElement("Name");
            name1.InnerText = "西游记";
            book1.AppendChild(name1);

            XmlElement price1 = doc.CreateElement("Price");
            price1.InnerText = "10";
            book1.AppendChild(price1);

            XmlElement des1 = doc.CreateElement("Des");
            des1.InnerText = "好看";
            book1.AppendChild(des1);

            XmlElement book2 = doc.CreateElement("Book");
            books.AppendChild(book2);


            XmlElement name2 = doc.CreateElement("Name");
            name2.InnerText = "西游记";
            book2.AppendChild(name2);

            XmlElement price2= doc.CreateElement("Price");
            price2.InnerText = "10";
            book2.AppendChild(price2);

            XmlElement des2 = doc.CreateElement("Des");
            des2.InnerText = "好看";
            book2.AppendChild(des2);

            doc.Save("Books.xml");
            Console.WriteLine("保存成功");
            Console.ReadKey();

38.创建带属性的XML文档

            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8","yes");
            doc.AppendChild(dec);

            XmlElement order = doc.CreateElement("Order");
            doc.AppendChild(order);

            XmlElement customerName = doc.CreateElement("CustomerName");
            customerName.InnerXml = "<p>我是一个p标签</p>";
            order.AppendChild(customerName);

            XmlElement customerNumber = doc.CreateElement("CustomerNumber");
            customerNumber.InnerText = "<p>我是一个p标签</p>";
            order.AppendChild(customerNumber);


            XmlElement items = doc.CreateElement("Items");
            order.AppendChild(items);

            XmlElement orderItem1 = doc.CreateElement("OrderItem");
            //给节点添加属性
            orderItem1.SetAttribute("Name", "充气娃娃");
            orderItem1.SetAttribute("Count", "10");
            items.AppendChild(orderItem1);

            XmlElement orderItem2 = doc.CreateElement("OrderItem");
            //给节点添加属性
            orderItem2.SetAttribute("Name", "充气娃娃");
            orderItem2.SetAttribute("Count", "10");
            items.AppendChild(orderItem2);

            XmlElement orderItem3 = doc.CreateElement("OrderItem");
            //给节点添加属性
            orderItem3.SetAttribute("Name", "充气娃娃");
            orderItem3.SetAttribute("Count", "10");
            items.AppendChild(orderItem3);

            doc.Save("Order.xml");
            Console.WriteLine("保存成功");
            Console.ReadKey();

39.追加XML

//追加XML文档
            XmlDocument doc = new XmlDocument();
            XmlElement books;
            if (File.Exists("Books.xml"))
            {
                //如果文件存在 加载XML
                doc.Load("Books.xml");
                //获得文件的根节点
                books = doc.DocumentElement;
            }
            else
            {
                //如果文件不存在
                //创建第一行
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                //创建跟节点
                books = doc.CreateElement("Books");
                doc.AppendChild(books);
            }
            //5、给根节点Books创建子节点
            XmlElement book1 = doc.CreateElement("Book");
            //将book添加到根节点
            books.AppendChild(book1);


            //6、给Book1添加子节点
            XmlElement name1 = doc.CreateElement("Name");
            name1.InnerText = "c#开发大全";
            book1.AppendChild(name1);

            XmlElement price1 = doc.CreateElement("Price");
            price1.InnerText = "110";
            book1.AppendChild(price1);

            XmlElement des1 = doc.CreateElement("Des");
            des1.InnerText = "看不懂";
            book1.AppendChild(des1);


            doc.Save("Books.xml");
            Console.WriteLine("保存成功");
            Console.ReadKey();

40.读取XML文档

//XmlDocument doc = new XmlDocument();
            ////加载要读取的XML
            //doc.Load("Books.xml");

            ////获得根节点
            //XmlElement books = doc.DocumentElement;

            ////获得子节点 返回节点的集合
            //XmlNodeList xnl = books.ChildNodes;

            //foreach (XmlNode item in xnl)
            //{
            //    Console.WriteLine(item.InnerText);
            //}
            //Console.ReadKey();


            //读取带属性的XML文档

            //XmlDocument doc = new XmlDocument();
            //doc.Load("Order.xml");
            //Xpath

            //XmlDocument doc = new XmlDocument();
            //doc.Load("Order.xml");
            //XmlNodeList xnl = doc.SelectNodes("/Order/Items/OrderItem");

            //foreach (XmlNode node in xnl)
            //{
            //    Console.WriteLine(node.Attributes["Name"].Value);
            //    Console.WriteLine(node.Attributes["Count"].Value);
            //}
            //Console.ReadKey();
            //改变属性的值
            //XmlDocument doc = new XmlDocument();
            //doc.Load("Order.xml");
            //XmlNode xn = doc.SelectSingleNode("/Order/Items/OrderItem[@Name='190']");
            //xn.Attributes["Count"].Value = "200";
            //xn.Attributes["Name"].Value = "颜世伟";
            //doc.Save("Order.xml");
            //Console.WriteLine("保存成功");




            XmlDocument doc = new XmlDocument();

            doc.Load("Order.xml");

            XmlNode xn = doc.SelectSingleNode("/Order/Items");

            xn.RemoveAll();
            doc.Save("Order.xml");
            Console.WriteLine("删除成功");
            Console.ReadKey();

            ////获得文档的根节点
            //XmlElement order = doc.DocumentElement;
            //XmlNodeList xnl = order.ChildNodes;
            //foreach (XmlNode item in xnl)
            //{
            //    ////如果不是Items 就continue
            //    //if (item[])
            //    //{
            //    //    continue;
            //    //}
            //    Console.WriteLine(item.Attributes["Name"].Value);
            //    Console.WriteLine(item.Attributes["Count"].Value);
            //}
            Console.ReadKey();

41.委托(将方法作为参数传递给方法)

public delegate void DelSayHi(string name);
    class Program
    {
        static void Main(string[] args)
        {
            //DelSayHi del = SayHiEnglish;//new DelSayHi(SayHiEnglish);
            //del("张三");
            //Console.ReadKey();

            //Test("张三", SayHiChinese);
            //Test("李四", SayHiEnglish);
            //Console.ReadKey();
        }

        public static void Test(string name,DelSayHi del)
        { 
            //调用
            del(name);
        }

        public static void SayHiChinese(string name)
        {
            Console.WriteLine("吃了么?" + name);
        }
        public static void SayHiEnglish(string name)
        {
            Console.WriteLine("Nice to meet you" + name);
        }
    }

42.匿名函数和lamda表达式

            //lamda表达式  => goes to
            DelSayHi del = (string name) => { Console.WriteLine("你好" + name); };
            del("张三");
            Console.ReadKey();

43.泛型委托

public delegate int DelCompare<T>(T t1, T t2);
    // public delegate int DelCompare(object o1, object o2);
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = { 1, 2, 3, 4, 5 };
            int max = GetMax<int>(nums, Compare1);
            Console.WriteLine(max);

            string[] names = { "abcdefg", "fdsfds", "fdsfdsfdsfdsfdsfdsfdsfsd" };
            string max1 = GetMax<string>(names, (string s1, string s2) =>
            {
                return s1.Length - s2.Length;
            });
            Console.WriteLine(max1);
            Console.ReadKey();
        }
        public static T GetMax<T>(T[] nums, DelCompare<T> del)
        {
            T max = nums[0];
            for (int i = 0; i < nums.Length; i++)
            {
                //要传一个比较的方法
                if (del(max, nums[i]) < 0)
                {
                    max = nums[i];
                }
            }
            return max;
        }


        public static int Compare1(int n1, int n2)
        {
            return n1 - n2;
        }
    }

44.单例模式

//全局唯一的单例
        public static Form2 FrmSingle=null;

        private Form2()
        {
            InitializeComponent();
        }

        public static Form2 GetSingle()
        {
            if (FrmSingle == null)
            {
                FrmSingle = new Form2();
            }
            return FrmSingle;
        }

45.多播委托

DelTest del = T1;
            del += T4;
            del += T1;
            del+= T2;
            //del -= T3;
            //del -= T1;
            del();
            Console.ReadKey();
        }

        public static void T1()
        {
            Console.WriteLine("我是T1");
        }
        public static void T2()
        {
            Console.WriteLine("我是T2");
        }

        public static void T3()
        {
            Console.WriteLine("我是T3");
        }
        public static void T4()
        {
            Console.WriteLine("我是T4");
        }
原文地址:https://www.cnblogs.com/mango1997/p/13966515.html