一个demo学会c#

全栈工程师开发手册 (作者:栾鹏)

c#教程全解

学习了c#4.5高级编程这本书,自己喜欢边学边总结边写demo,所以写了这篇文章,包含了大部分的c#编程知识。让你一个demo掌握c#编程,如果有问题可以留言。
此demo主要包括五个文件:Students.cs和Moniter.cs文件,包含了自定义空间、空间函数、空间变量、空间自定义类;Interface1.cs文件和Interface2.cs文件为接口文件;index.cs文件为主程序运算。

Students.cs和Moniter.cs文件包含了自定义基、继承类、模板类的定义及实现。涉及到自定义类的构造函数、重载构造函数、函数默认值、析构函数、复制构造函数、重载运算符(赋值函数、加法函数)、虚函数、常值函数、静态函数、静态变量、常值变量、枚举变量、内部类、访问修饰符、继承、重写虚函数、基类引用、不定参数函数、友函数、友类、类型引用、终态函数、终态类、模板变量等内容。

Students.cs文件内容如下:

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

namespace csharpdemo
{
    //自定义结构体,值类型
    struct People
    {
        string name;
        int id;
    }
    //static int vartemp=10;    //禁止使用脱离类的全局数据
    //自定义类,引用类型。一个文件可以包含多个类,类默认为修饰符为私有
    public class Student : IComparable<Student>
    {
        public static void main(String[] args) { }                                              //每个类中都可以有一个main函数,用于调试
        static Student() { default_name = "student"; }                                          //静态构造函数,在第一次调用类的任何成员之前,仅执行一次,不能有参数,不用访问修饰符,且只有有一个
        public Student()                                                                        //自定义无参构造器,没有自定义构造器时,编译器会生成默认无参构造器,
            : this("student", 12)                                                               //通过this仅能调用一个构造器,必须将构造器调用置于起始处
        {
            getname();
            Console.WriteLine("基类无参构造器创建了一个对象");
        }
        public Student(string name,int age){                                                    //有参构造器,设置int age=12为默认值,可单参数调用
            this.age = age; this.name = name;
            Console.WriteLine("基类有参构造器创建了一个对象");
        }
        public Student(string name,params object[] args)                                        //可变参数列表,args是一个参数列表,重载方法中应该只有一个使用可变参数列表,且位于参数的最后面,编译器会自动调用最符合的重载函数执行
        {
            this.name = name; Console.WriteLine("基类变参构造器开辟了一个对象");                //args[0]为变参中的第一个参数
        }
        ~Student() { Console.WriteLine("基类析构函数"); }                                       //析构函数
        public static Student operator +(Student student1, Student student2)                    //运算符重载  +号运算  可以重载多种运算。
        {
            Student student = new Student(student1.name+student2.name);
            return student;
        }
        public static Student operator +(Student student1, string name2)                        //运算符重载,为避免重载时的隐式转化,+必须位于student变量的后面
        {
            Student student = new Student(student1.name + name2);
            return student;
        }
        public void setname(string name) { Console.WriteLine("基类设置名称" + name); this.name = name; }  //this表示对当前对象的引用
        public virtual string getname() { Console.WriteLine("基类获取名称" + name); return name; }   //使用public方法实现对private数据的控制,保证类内数据安全
        public string tast { get; private set; }                                                    //自动实现属性访问设置器
        internal void setage (ref int age){Console.WriteLine("基类设置年龄"+age);this.age=age;}     //ref传递引用
        public virtual void getage(out int age){age=this.age;}                                      //out对未初始化的变量进行保留改变,virtual虚函数不能私有
        internal static long time = 10;                                                             //数据均可在定义时初始化,internal引用当前类的所有类可见
        private int age = 0;                                                                        //private外部不可以访问
        public string name = "student";   
        static string default_name;
        public const int default_age = 12;                                                          //const定义常量,定义时赋值,不能是static
        public Sextype sextype = new Sextype();                                                     //访问内部类,编译器自动生成构造器
        public enum allsex { man, woman }                                                           //枚举类型,等价于类内组合class allsex{man,woman}
        public class Sextype                                                                        //内部类,无法通过内部类返回外部类的引用,当内部类声明为static时为嵌套类,嵌套类不属于对象,而属于类名
        {
            public void setsex(allsex sextype)
            {
                switch (sextype)
                {
                    case allsex.man: sexstring = "man"; break;
                    case allsex.woman: sexstring = "woman"; break;
                    default:break;
                }
            }
            private string sexstring;
        }

        //重写equals虚函数,重写equals必须重写gethashcode否则发生警告
        public override bool Equals(object another)
        {
            Console.WriteLine("比较了两个基类");
            if (this.age == ((Student)another).age && this.name == ((Student)another).name)
                return true;
            return false;
        }

        //重写散列函数
        public override int GetHashCode()
        {
            return base.GetHashCode();                                                              //调用基类的散列函数
        }
        //实现比较函数
        public int CompareTo(Student arg0)                                                          //要实现排序,必须要实现比较接口
        {
            return age < arg0.age ? -1 : (age == arg0.age ? 0 : 1);                                 //返回-1表示小于,0表示等于,1表示大于
        }
    }



    //一个文件可以包含多个类,
    abstract class Teacher                                                                          //abstract声明抽象类或抽象函数
    {
        public abstract void setname();                                                             //abstract抽象方法
        public string getname() { return name;}                                                     //使用public方法实现对private数据的控制
        string name = "teacher";                                                                    //不加修饰符默认为?
    }
    sealed class president<T> : Teacher                                                             //派生类如果不是抽象,必须重写全部抽象函数,sealed终态,不能再被继承
    {
        public sealed override void setname() { }                                                   //sealed函数不能重写,重写必须要添加override
        private T tt;                                                                               //设置泛型,也可以使用基本原型object
        public T getT() { return tt; }                                                              //设置泛型函数,泛型会自动擦除传递过来的对象的类信息
        public void setT(T tt) { tt = default(T); this.tt = tt; }                                   //default获取默认值,引用为null,值类型为0
    }
}

Moniter.cs文件内容如下:

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

namespace csharpdemo
{
public class Moniter:Student,Interface2<String>                                 //可以包含多个接口,实现泛型接口
{
    public Moniter():base("monitor"){                                           //派生类构造器,关键字base显示调用基类构造器
        Console.WriteLine("派生类无参构造器创建了对象" + name);
    }
    public Moniter(int age){                                                    //派生类单参数构造器
        Console.WriteLine("派生类有参构造器创建了对象"+name);
    }
    static Student mystudent = new Student("moniter",12);                       //静态对象初始化只在使用时刻在进行,在第一个创建类对象或者第一次访问静态数据时才初始化

    //重写函数的返回类型可以是基类此方法的返回类型的派生类型
    public override string getname()                                            //重写虚函数需要override关键字
    {
        Console.WriteLine("派生类获取名称" + name);
        //name = base.name + "的派生";
        return name;
    }
    public int getage() { return 11; }                                          //private不能重写,派生类重名,覆盖基类私有方法


    new string name = "moniter";                                                //同名变量和静态变量,不动态绑定到基类引用上,和基类数据存储在不同的区域,new关键字隐藏基类成员
    string task = "帮助老师管理班级";

    public void init1()                                                         //实现接口函数不叫重写,所以不加override。多接口时应避免接口函数同名
    {
        Console.WriteLine("实现接口1初始化函数,或接口2初始化函数");
    }
    public void init2(String name)                                              //泛型接口
    {
        Console.WriteLine("实现接口2初始化函数");
    }


}
}

Interface1.cs文件内容如下:

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

namespace csharpdemo
{
    public interface Interface1         //interface接口,完全抽象类,接口中不能包含字段
    {
        void init1();                   //abstract抽象方法,接口自动是public的,接口中,不能有函数定义体,abstract可以不写
    }
}

Interface2.cs文件内容如下:

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

namespace csharpdemo
{
    //in抗变泛型,不能使用向上转型来实现泛型方法,接口也支持继承,接口可以多继承,extends后可以有多个子接口,接口可以嵌套在类中<A>泛型接口
    interface Interface2<in T>:Interface1
    {
        void init2(T name);             //abstract抽象方法,接口自动是public
        new void init1();               //接口隐藏了基接口的函数
    }
}

Index.cs主程序文件内容如下:

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

namespace csharpdemo
{
    using System.Text.RegularExpressions;                                               //using为已有类型声明提供一个新民称
    using myint = System.IntPtr;
    class index                                                                         //自定义类可以添加static,静态类不能实例化
    {
        static String stringtemp = "栾鹏调试";
        static void Main(string[] args)
        {
            var default_age = -2 * -6;                                                  //var类型推断,局部变量必须显示初始化,基本类型也通过对象object兑现,只不过只存储值,是值类型,一元减号用于转变数据的符号
            const string default_name = "student";                                      //const常量,编译时用于计算,不能使用变量对其赋值
            var students=new {name="students",age=12};                                  //匿名类型(在实例化时定义)var类型推断

            Student.time+=Student.time<<2+0x21^26;                                      //静态数据,可以直接通过类名访问,<<位左移动,低位补零,^按位异或,0x表示16进制数
            Student student1 = new Student();                                           //所有的对象都必须通过new来创建,基本数据类型可以定义创建
            student1.name = student1.getname()+1;                                       //访问类内数据,字符串+重载
            student1.setage(ref default_age);                                           //通过类内函数访问数据
            Student.Sextype student1_sextype = new Student.Sextype();                   //创建内部类,必须通过外部类变量new构造
            student1_sextype.setsex(Student.allsex.man);                                //调用枚举类型
            Student student2 = student1;                                                //仅复制引用,两个变量名指向同一块内存,可通过实现浅拷贝IShallowCopy和深拷贝IDeepCopy实现全面复制
            if (student1==student2)                                                     //==和!=只是比较对象的引用,不比较对象内容
                if(student1.Equals(student2))                                           //对象的比较使用equals,但是默认的equals还是比较引用,要在自定义类中重写equals
                    if(default_age is object)                                           //非布尔值不能用在逻辑表达式中,is检测对象是否与类型兼容,int数据也是object继承来的
                        printf("创建了两个相同的类");

            Random random=new Random();                                                 //随机数
            int[,] farray = new int[2,3];                                               //锯齿数组[2][3],二维数组[2,3]
            farray[0,0]=random.Next(10,100);                                            //读取伪随机序列
            Moniter sub1 = new Moniter();                                               //基类构造函数(绑定后函数),派生类成员,派生类构造函数,接口中的域相当于枚举常量
            sprintf(sub1,null);                                                         //可变参数,null为空参数
            sprintf(sub1);                                                              //传递实现接口的类,向上转化为接口,实现函数回调
            Student student3 = new Moniter();                                           //基类引用,派生类对象
            student3.getname();                                                         //调用引用动态绑定的方法
            ((Moniter)student3).getage();                                               //向下转型成功
            Interface1 interface1 = new Moniter();                                      //向上转型,interface1是基类,接口,无所谓,实现接口的类(包含内部类),都可以向上转化为接口
            interface1.init1();                                                         //调用动态绑定的函数

            List<String> allname=new List<String>(){"小明","晓刚","小红","晓刚","小刘"};
            allname[allname.IndexOf(allname[3])]="小刚";                                  //[]读取元素,indexof搜索,没有返回-1,
            if(!allname.Contains("小王"))                                                 //包含元素
                allname.Add("小王");                                                      //添加元素
            allname.RemoveAt(4);                                                          //删除下标元素
            allname.Insert(1,"小韩");                                                     //插入元素
            allname.Sort();                                                               //排序

            //link查询,类似于数据查询语句,查询操作本地数据集(数据集类似于二维表)查询语句就是单个元素的判断
            var query = from names in allname where names.StartsWith("小") && names.Length==2 orderby names.Length select names;
            foreach(String item in query)                                                  //foreach遍历时,link语句才执行
                Console.WriteLine(item);

            //list,set,dictionary
            Queue<String> allname0=new Queue<String>();                                     //队列count元素个数,Enqueue入队,Dequeue出队,Peek读取头,trimexcess重设容量
            Stack<String> allname1= new Stack<String>();                                    //stack先入后出 堆栈 各种队列和栈基于linked链表实现,count元素个数,push栈顶添加元素,pop栈顶删除元素,contains是否存在
            LinkedList<String> allname2 = new LinkedList<String>();                         //双端队列,队列,双向链表
            HashSet<String> allname3 = new HashSet<String>();                               //包含不重复元素的无序列表
            SortedSet<String> allname4 = new SortedSet<String>();                           //包含不重复的有序集合
            var allstudent1 = new SortedList<int,string>();                                 //有序列表
            //sorteddictionary有序字典,键通过gethashcode映射到索引(数组),索引关连值。多个键可以映射到一个索引,一个索引可以关联多个值
            Dictionary<int,string> allstudent2=new Dictionary<int,string>();



            try                                                                             //尝试执行
            {
                StringBuilder sb = new StringBuilder();                                     //stringbuilder包括insert、replace、substring、reverse、append、tostring、delete
                sb.Append(String.Format("这里%s字符串相关操作类","shi"));                   //string.format()   格式化函数,内部创建formatter类设置字符串格式
                String outstr = sb.ToString().Replace("shi","是");                          //string是不可变量,取值变化是生成新的类,replace替换,replaceall,replacefirst
                outstr+=outstr.Substring(3)+outstr.Length;                                  //substring取子字符串,length字符串长度字段,+重载
                if(outstr.IndexOf("shi")<0)                                                 //indexof查询子字符串的位置,不存在范围-1,其他字符串相关操作较多
                    printf("字符串不存在子字符串");
                outstr="luanpeng luanpeng";
                outstr = Regex.Split(outstr," ",RegexOptions.IgnoreCase)[0];                //split字符串分割,返回数组,IgnoreCase忽略大小写
                string patter = "l.an";                                                     //创建正则表达式
                MatchCollection matcher = Regex.Matches(outstr,patter,RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture);   //创建匹配器
                foreach(Match nextmatch in matcher)                                         //依次查询是否存在匹配
                    printf(nextmatch.Index);                                                //匹配位置

                //int aa=0/0;

            }
            catch (System.Exception ex)                                                     //catch函数在try出错时调用,exception为所有异常的基类,异常可以捕获派生类异常
            {
                printf("错误内容:"+ex.ToString());
                Console.WriteLine(ex.StackTrace);
            }
            finally                                                                         //finally函数总要执行
            {
                printf("finally函数总要执行");
            }

            Student[] all1 = new Student[7];  //
            Student[] all2 = new Student[10];
            all2=(Student[])all1.Clone();                                                   //复制数组,数组元素为引用,则辅助数组的每一个引用项,引用对象数据不复制
            Array.Sort(all2);                                                               //调用重写的排序函数执行数组排序
            int location = Array.BinarySearch(all2,student1);                               //在数组中查询,不存在范围-1

            president<Student> sub2 = new president<Student>();                             //包含泛型的类型调用,也可以不使用泛型创建对象
            sub2.setT(student1);                                                            //将使用类型替换泛型


            //注解
            //数据流
            //序列化
            //Task为后台线程,线程池线程适合运行短时间程序,均为后台线程,不能设置优先级
            run();                                                                          //在主线程中调用run函数
            Parallel.For(2,4,i=>{num=i;run();});                                            //Parallel.For并行for循环,没有顺序,参数i从2到4(不包括4),可以设置提前终止条件
            Parallel.ForEach<string>(allname,str=>{stringtemp=str;run();});                 //Parallel.ForEach并行遍历,没有顺序,可以设置提前终止条件
            Parallel.Invoke(run,run);                                                       //并行运行多个委托
            Task t1 = new Task(run);                                                        //可以创建时向函数传递参数,新任务,使用线程池中的线程
            t1 = new TaskFactory().StartNew(run);                                           //创建任务工厂,并创建启动新线程,使用线程池中的线程
            t1 = Task.Factory.StartNew(run);                                                //静态属性factory创建,使用线程池中的线程
            t1=Task.Run(()=>{run();});                                                      //lambda表达式为参数重写task的run函数,使用线程池中的线程
            //t1.RunSynchronously();                                                        //在当前线程(主线程),启动任务
            t1=new Task(run,TaskCreationOptions.LongRunning);                               //新线程,不使用线程池中的线程
            t1.Start();
            t1.Wait();                                                                      //等待执行完成
            //ThreadPool.QueueUserWorkItem(run);                                            //选择线程池中的线程执行函数,没有创建线程池会先创建再执行

            //thread默认是前台线程,适合运行长时间函数
            Thread thread =new Thread(run);                                                 //调用子线程,执行run函数
            thread=new Thread(()=>Console.WriteLine("lambda线程函数"));                     //调用lambda表达式线程函数
            thread.IsBackground=true;                                                       //设置为后台线程
            thread.Priority = ThreadPriority.Highest;                                       //设置线程优先级
            thread.Start();                                                                 //启动线程Start()括号中可以包含一个参数
            thread.Join();                                                                  //等待线程结束
            thread.Abort();                                                                 //线程中断,会在线程运行至阻塞时中断
            new Thread(run).Start();                                                        //新建线程执行函数

            //lock(锁定资源)、Interlocked(提供线程安全的递增递减交换和读取值)、Monitor(设置超时,释放锁)、waitHandle(等待信号的出现)
            //mutex(多个进程间同步-通过名称)、semaphore(信号量可以由多个线程使用)、event(事件通知)
            bool locktaken=false;
            Monitor.TryEnter(stringtemp,500,ref locktaken);
            if (locktaken){
               printf("同步控制块执行");
                Monitor.Exit(stringtemp);                                                   //释放锁
            }

            //在threading、timers、forms、web ui、windows.threading中都有timer,设置重复执行的函数
            //System.Timers.Timer mytime= new System.Timers.Timer(1000);
            //mytime.AutoReset = true;
            //mytime.Elapsed+=run;   //回调函数参数受到限制的(object sender,system.timers.elapsedeventargs e)
            //mytime.Start();
            //mytime.Stop();

            Showdata datashowfun = new Showdata(printf);                                     //以函数为参数实例化委托,作为回调函数
            datashowfun = delegate(string str){Console.WriteLine(str);};                     //使用匿名方法实现委托
            datashowfun = str=>{Console.WriteLine(str+stringtemp);};                         //使用lambda表达式实现委托,lambda表达式可以访问外部变量,这成为闭包。=>左边列出参数,右边复制实现函数
            print(datashowfun,"结束");                                                       //委托为参数,调用函数

            Console.ReadLine();

        }


        public static void sprintf(Student student, object[] args)                          //基类参数允许传递派生类为参数,object[]用于可变参数列表,可以无参调用
        {
            student.setname("student");                                                     //调用动态绑定的基类函数,修改基类成员
            printf(student.getname());                                                      //调用引用动态绑定的派生类重写的函数
        }
        public static void sprintf(Interface1 interface1)                                   //接口参数允许传递接口类为参数,sprintf函数名相同实现重载
        {
            if (interface1 is Moniter)                                                      //is判断,指向对象的具体判断,不是引用的判断
            {
                Student student = interface1 as Student;                                    //先向下转型为Moniter,在向上转型为student,as向上转型,在指定派生类对象的基类引用,可以强制转化为派生类引用
                printf("接口类型:" + interface1.GetType());                                //获取引用指向的对象的类型
                student.getname();                                                          //动态调用绑定的方法
            }
            interface1.init1();                                                             //接口相当于纯抽象类,动态绑定方法
        }

        public static void printf<T>(T str)                                                 //泛型方法,
        {
            Console.WriteLine(str.ToString());  
        }

        public delegate void Showdata(string str);                                          //delegate定义委托,委托名为函数类型名,而不是函数变量名。这是一个输入为字符串,返回为空的函数引用,
        public static void print(Showdata action, string str)
        {
            action(str);
        }

        static int num = 0;
        public static void run()
        {
            num++;                                                                          //自增自减不是线程安全的
            Thread.Sleep(1000);                                                             //多线程,睡眠,不释放锁,自动回复
            //await Task.Delay(10);                                                         //await一旦完成立即执行,Task.Delay异步方法,释放线程供其他任务使用,所以此句后面的是新线程
            printf(num + stringtemp + DateTime.Now);
        }

    }
}

猜你喜欢

转载自blog.csdn.net/luanpeng825485697/article/details/76570701