C#高级篇(二)---LINQ、反射、线程

来源:互联网 发布:js 获取http 的状态 编辑:程序博客网 时间:2024/05/17 09:08

LINQ用法

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace _013_LINQ {    class Kongfu {        public int Id { get; set; }        public string Name { get; set; }        public int Power { get; set; }        public override string ToString()        {            return string.Format("Id: {0}, Name: {1}, Power: {2}", Id, Name, Power);        }    }}

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace _013_LINQ {    class MartialArtsMaster {        public int Id { get; set; }        public string Name { get; set; }        public int Age { get; set; }        public string Menpai { get; set; }        public string Kongfu { get; set; }        public int Level { get; set; }        public override string ToString()        {            return string.Format("Id: {0}, Name: {1}, Age: {2}, Menpai: {3}, Kongfu: {4}, Level: {5}", Id, Name, Age, Menpai, Kongfu, Level);        }    }}

using System;using System.Collections.Generic;using System.Linq;using System.Security.Cryptography;using System.Text;using System.Threading.Tasks;namespace _013_LINQ{    internal class Program    {        private static void Main(string[] args)        {            //初始化武林高手            var masterList = new List<MartialArtsMaster>()            {                new MartialArtsMaster() {Id = 1, Name = "黄蓉", Age = 18, Menpai = "丐帮", Kongfu = "打狗棒法", Level = 9},                               new MartialArtsMaster() {Id = 4, Name = "任我行", Age = 50, Menpai = "明教", Kongfu = "葵花宝典", Level = 1},                                new MartialArtsMaster() {Id = 6, Name = "林平之", Age = 23, Menpai = "华山", Kongfu = "葵花宝典", Level = 7},                                new MartialArtsMaster() {Id = 10, Name = "黄药师", Age = 23, Menpai = "梅花岛", Kongfu = "弹指神通", Level = 10},                          };            //初始化武学            var kongfuList = new List<Kongfu>()            {                new Kongfu() {Id = 1, Name = "打狗棒法", Power = 90},                new Kongfu() {Id = 2, Name = "降龙十八掌", Power = 95},                new Kongfu() {Id = 3, Name = "葵花宝典", Power = 100},                new Kongfu() {Id = 4, Name = "独孤九剑", Power = 100},                new Kongfu() {Id = 5, Name = "九阴真经", Power = 100},                new Kongfu() {Id = 6, Name = "弹指神通", Power = 100}            };            //查询所有武学级别大于8的武林高手            var res = new List<MartialArtsMaster>();            foreach (var temp in masterList)            {                if (temp.Level > 8)                {                    res.Add(temp);                }            }            //1,使用LINQ做查询( 表达式写法)            //从masterList查询,每个取名为m            var res1 = from m in masterList                      //where后面跟上查询的条件                      where m.Level > 8 && m.Menpai == "丐帮"                      select m;//表示m的结果集合返回            foreach (var temp in res1)            {                Console.WriteLine(temp);            }            Console.WriteLine();            //2.1扩展方法的写法--匿名函数            //参数是Func委托,返回值是bool类型--用来过滤                        var res2 = masterList.Where(Test1);            foreach (var temp in res2)            {                Console.WriteLine(temp);            }            Console.WriteLine();            //2.2扩展方法的写法--lanbda表达式            var res3 = masterList.Where(m => m.Level > 8 && m.Menpai == "丐帮");            foreach (var temp in res3)            {                Console.WriteLine(temp);            }            Console.WriteLine();            //3,LINQ 联合查询            //取得所学功夫的杀伤力大于90 的武林高手            var res4 = from m in masterList                      from k in kongfuList                      where m.Kongfu == k.Name && k.Power > 90                      //select new {master = m, kongfu = k};                      select m;            foreach (var temp in res4)            {                Console.WriteLine(temp);            }            Console.WriteLine();            //扩展方法用法            //var res =            //    masterList.SelectMany(m => kongfuList, (m, k) => new {master = m, kongfu = k})            //        .Where(x => x.master.Kongfu == x.kongfu.Name && x.kongfu.Power>90 );            //4,对查询结果做排序 orderby (descending)            var res5 = from m in masterList                          //from后面设置查询的集合                      where m.Level > 8 && m.Menpai == "丐帮" //通过&&添加并列的条件                      //orderby m.Age descending                      orderby m.Level, m.Age //按照多个字段进行排序,如果字段的属性相同,就按照第二个属性排序                      //where后面跟上查询的条件                      select m;//表示m的结果结合返回            foreach (var temp in res5)            {                Console.WriteLine(temp);            }            Console.WriteLine();            //var res = masterList.Where(m => m.Level > 8 && m.Menpai == "丐帮").OrderBy(m => m.Age);            //var res = masterList.Where(m => m.Level > 8).OrderBy(m => m.Level).ThenBy(m => m.Age);            //5,join on 集合联合--on連接條件            var res6 = from m in masterList                      join k in kongfuList on m.Kongfu equals k.Name                      where k.Power == 100                      select new { master = m, kongfu = k };            foreach (var temp in res6)            {                Console.WriteLine(temp);            }            Console.WriteLine();            //6,分组查询 into groups (把武林高手按照所学功夫分类,看一下那个功夫修炼的人数最多)            var res7 = from k in kongfuList                      join m in masterList on k.Name equals m.Kongfu                      into groups                      orderby groups.Count()                      select new { kongfu = k, count = groups.Count() };            foreach (var temp in res6)            {                Console.WriteLine(temp);            }            Console.WriteLine();            //7,量词操作符 any all 判断集合中是否满足某个条件            bool res8 = masterList.Any(m => m.Menpai == "长留");            Console.WriteLine(res);            Console.WriteLine();            bool res9 = masterList.All(m => m.Menpai == "丐帮");            Console.WriteLine(res);            Console.WriteLine();            Console.ReadKey();        }        //过滤方法--返回值为布尔类型--集合内部遍历元素,每个元素掉用该方法,返回为true会被过滤出来被选中,        //返回false,会被过滤掉        static bool Test1(MartialArtsMaster master)        {            if (master.Level > 8) return true;            return false;        }    }}



反射

<pre name="code" class="csharp">using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace _014_反射和特性 {    class MyClass    {        private int id;        private int age;        public int number;        public string Name { get; set; }        public string Name2 { get; set; }        public string Name3 { get; set; }        public void Test1() {        }        public void Test2() {        }    }}


using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;namespace _014_反射和特性 {    class Program {        static void Main(string[] args) {            //每一个类对应一个type对象,这个type对象存储了这个类 有哪些方法跟哪些数据 哪些成员            MyClass my = new MyClass();//一个类中的数据 是存储在对象中的, 但是type对象只存储类的成员            Type type = my.GetType();//通过对象获取这个对象所属类 的Type对象            Console.WriteLine(type.Name);//获取类的名字            Console.WriteLine(type.Namespace);//获取所在的命名空间            Console.WriteLine(type.Assembly);            //1、只能获取public 字段            FieldInfo[] array = type.GetFields();            foreach (FieldInfo info in array)            {                Console.Write(info.Name + " ");            }            Console.WriteLine();            //2、獲取屬性            PropertyInfo[] array2 = type.GetProperties();            foreach (PropertyInfo info in array2)            {                Console.Write(info.Name + " ");            }            Console.WriteLine();            //3、獲取方法            MethodInfo[] array3 = type.GetMethods();            foreach (MethodInfo info in array3)            {                Console.Write(info.Name + " ");            }            Console.WriteLine();            //通过type对象可以获取它对应的类的所有成员(public)            Console.ReadKey();        }    }}


新特性

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Text;using System.Threading.Tasks;namespace _015_特性 {    //1, 特性类的后缀以Attribute结尾     //2, 需要继承自System.Attribute    //3, 一般情况下声明为 sealed    //4, 一般情况下 特性类用来表示目标结构的一些状态(定义一些字段或者属性, 一般不定义方法)    [AttributeUsage(AttributeTargets.Class)]//表示该特性类可以应用到的程序结构有哪些    sealed class MyTestAttribute : System.Attribute {        public string Description { get; set; }        public string VersionNumber { get; set; }        public int ID { get; set; }        public MyTestAttribute(string des)        {            this.Description = des;        }    }}

#define IsTest //定义一个宏Test1 才可以运行using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Runtime.CompilerServices;using System.Text;using System.Threading.Tasks;namespace _015_特性 {    //3、通过制定属性的名字,给属性赋值,这种事命名参数    //当我们使用特性的时候,后面的Attribute不需要写    [MyTest("简单的特性类",ID = 100)]    class Program {        //1、obsolete特性用来表示一个方法被弃用了        [Obsolete("这个方法过时了,使用NewMethod代替")]         static void OldMethod()        {            Console.WriteLine("Oldmethod");        }        static void NewMethod()        {                    }        //2、定义宏        [Conditional("IsTest")]        static void Test1() {            Console.WriteLine("test1");        }        static void Test2() {            Console.WriteLine("test2");        }        static void Main(string[] args) {            NewMethod();            OldMethod();            Test1();            Test2();            Test1();            Type type = typeof (Program);//通过typeof+类名也可以获取type对象            //获取特性类的属性--那些利用了特性            object[] array = type.GetCustomAttributes(false);            MyTestAttribute mytest = array[0] as MyTestAttribute;            Console.WriteLine(mytest.Description);            Console.WriteLine(mytest.ID);            Console.ReadKey();        }    }}


委托方式发起线程

using System;using System.Collections.Generic;using System.Linq;using System.Net.NetworkInformation;using System.Text;using System.Threading;using System.Threading.Tasks;namespace _016_线程_委托方式发起线程 {    class Program {        //一般我们会为比较耗时的操作 开启单独的线程去执行,比如下载操作        static int Test(int i,string str)        {            Console.WriteLine("test"+i+str);            Thread.Sleep(100);//让当亲线程休眠(暂停线程的执行) 单位ms            return 100;        }        //1、通过action委托开启线程        static void Test1(int i)        {            Console.WriteLine("test" + i );            Console.WriteLine();        }        static void Main(string[] args) {//在main线程中执行 一个线程里面语句的执行 是从上到下的            //1、通过action委托开启线程            Action<int> aa = Test1;            aa.BeginInvoke(100, null, null);            Console.WriteLine("main");            //2,通过委托 开启一个线程            Func<int, string, int> a = Test;            // 开启一个新的线程去执行 a所引用的方法,异步执行的,方法执行完毕,才可以获取返回值            IAsyncResult ar = a.BeginInvoke(100, "siki", null, null);            Console.WriteLine("main");            //检测线程结束            //1000毫秒表示超时时间,如果等待了1000毫秒 线程还没有结束的话 那么这个方法会返回false             //如果在1000毫秒以内线程结束了,那么这个方法会返回true            bool isEnd = ar.AsyncWaitHandle.WaitOne(1);            if (isEnd)            {                int res3 = a.EndInvoke(ar);                Console.WriteLine(res3);            }            else            {                Console.WriteLine("no end");            }            //如果当前线程没有执行完毕            while (ar.IsCompleted == false)            {                Console.Write(".");                Thread.Sleep(10); //控制子线程的检测频率            }            int res = a.EndInvoke(ar);//取得异步线程的返回值            Console.WriteLine(res);            Console.WriteLine();            //3、通过回调 检测线程结束            Func<int, string, int> aFunc = Test;            //倒数第二个参数是一个委托类型的参数,表示回调函数            //就是当线程结束的时候会调用这个委托指向的方法 倒数第一个参数用来给回调函数传递数据            IAsyncResult ar0 = aFunc.BeginInvoke(100, "siki", OnCallBack, aFunc);// 开启一个新的线程去执行 a所引用的方法             Console.WriteLine();            //4、通过lambda表达式获取            Func<int, string, int> aFunc1 = Test;            aFunc1.BeginInvoke(100, "siki", ar11 =>            {                if(ar11.IsCompleted == true){                int res1 = aFunc1.EndInvoke(ar11);                Console.WriteLine(res1 + "在lambda表达式中取得");                                }            }, null);            Console.ReadKey();        }        static void OnCallBack( IAsyncResult ar )        {            Func<int, string, int> a = ar.AsyncState as Func<int, string, int>;            if(ar.IsCompleted == true){            int res =  a.EndInvoke(ar);            Console.WriteLine(res+"在回调函数中取得结果");                        }        }    }}



通过Thread类开启线程服务

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace _017_线程_通过Thread发起线程 {    class MyThread    {        private string filename;        private string filepath;        public MyThread(string fileName, string filePath)        {            this.filename = fileName;            this.filepath = filePath;        }        public void DownFile()        {            Console.WriteLine("开始下载"+filepath+filename);            Thread.Sleep(20000);            Console.WriteLine("下载完成");        }    }}

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace _017_线程_通过Thread发起线程 {    class Program {        static void DownloadFile(object filename)        {            Console.WriteLine("开始下载:"  +Thread.CurrentThread.ManagedThreadId +filename);            Thread.Sleep(20000);            Console.WriteLine("下载完成");        }        static void Main(string[] args) {            //1、通过Thread创建线程            Thread t = new Thread(DownloadFile);            t.Start();            Console.WriteLine("Main");            //2、利用表达式创建线程            Thread t1 = new Thread(() =>            {                Console.WriteLine("开始下载:" + Thread.CurrentThread.ManagedThreadId);                Thread.Sleep(20000);                Console.WriteLine("下载完成");            });            t1.Start();            //3、传递值            Thread t3 = new Thread(DownloadFile);//创建出来Thread对象,这个线程并没有启动            t3.Start("xxx.种子");//开始,开始去执行线程            Console.WriteLine("Main");            //4、自定义MyThread线程            MyThread my = new MyThread("xxx.bt", "http://www.xxx.bbs");            Thread t4 = new Thread(my.DownFile);//我们构造一个thread对象的时候,可以传递一个静态方法,也可以传递一个对象的普通方法            t4.Start();                  }    }}



线程池

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace _018_线程_线程池 {    class Program {        static void ThreadMethod(object state)        {            Console.WriteLine("线程开始:"+Thread.CurrentThread.ManagedThreadId);            Thread.Sleep(2000);            Console.WriteLine("线程结束");        }        static void TaskMethod()        {            Console.WriteLine("任务开始");            Thread.Sleep(2000);            Console.WriteLine("任务结束");        }        static void Main(string[] args)        {            //1、线程池            ThreadPool.QueueUserWorkItem(ThreadMethod);//开启一个工作线程            ThreadPool.QueueUserWorkItem(ThreadMethod);            ThreadPool.QueueUserWorkItem(ThreadMethod);            ThreadPool.QueueUserWorkItem(ThreadMethod);            ThreadPool.QueueUserWorkItem(ThreadMethod);            ThreadPool.QueueUserWorkItem(ThreadMethod);            ThreadPool.QueueUserWorkItem(ThreadMethod);            //2、Task线程            Task t = new Task(TaskMethod);//传递一个需要线程去执行的方法            t.Start();            //3、TaskFactory线程            TaskFactory tf = new TaskFactory();            tf.StartNew(TaskMethod);                       Console.ReadKey();        }    }}


0 0
原创粉丝点击