.Net Core学习01


杨中科教程
.net Core 代码跨平台应用

.Net Framework缺点
  1. 系统级别的安装,互相影响(不同版本不兼容,耦合程度高)
  2. 无法独立部署。需要对方安装对应版本
  3. ASP.NET 和IIS深度耦合
  4. 资源消耗大
  5. 非云原生
.Net Core优点
  1. 支持独立部署,不互相影响
  2. 彻底模块化
  3. 不依赖IIS
  4. 跨平台
  5. 没有历史包袱,运行效率高

.Net standard只是一个标准一个规范
被Core,Framework引用。
在这里插入图片描述
.csproj 项目信息
.net framework csproj白名单 添加信息
.net core 黑名单 移除信息

项目发布

项目右键,发布

部署模式 依赖框架需要目标机上有环境,所以一般选独立

目标运行时 在什么系统

ReadyToRun 加快启动速度,加长编译时间,二进制文件更大

剪裁未使用程序集,删掉没用的

.pdb是调试文件

虚拟机推荐软件
内置window虚拟机
Windows Sandbox
内置linux虚拟机
wsl windows subsystem for linux

NuGet

newGet 最新

查包网站

在这里插入图片描述
工具->NutGet包管理器->控制台
在这里插入图片描述
安装成功后在项目文件有显示
在这里插入图片描述

卸载 Uninstall-Package 包名
更新 Update-Package 包名

异步编程

不等
对于单个事件时间效率没有提升,但能同时处理个同样事件,处理完再往下走。。

using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace awaitasynv1
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            //string filename = @"1.txt";

            //StringBuilder sb = new StringBuilder();

            //System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            //stopwatch.Start();

            //for (int i = 0; i < 10000; i++)
            //{
            //    sb.AppendLine("hello");
            //}

            //File.WriteAllText(filename, sb.ToString());
            //string s = File.ReadAllText(filename);

            //Console.WriteLine(s);
            //stopwatch.Stop();
            //Console.WriteLine(stopwatch.Elapsed.Milliseconds);

            string filename = @"1.txt";
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 10000; i++)
            {
                sb.AppendLine("hello");
            }

            await File.WriteAllTextAsync(filename, sb.ToString());

            //Task<string> t = File.ReadAllTextAsync(filename);
            //string b = await t;
            //自动把返回值从 Task取出来
            string s = await File.ReadAllTextAsync(filename);
            Console.WriteLine(s);
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed.Milliseconds);
        }
    }
}

在线程里进行异步调用
using System;
using System.IO;
using System.Threading;

namespace async03
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(async (obj) =>
            {
               while(true)
                {
                    //Console.WriteLine("xxxxxxxxxx");
                    await File.WriteAllTextAsync("1.txt", "111111");
                }
            });
            Console.Read();
        }
    }
}

await,async是语法糖,最终编译成状态机调用
在这里插入图片描述
在这里插入图片描述
async标记的方法中没有await会被当做同步方法处理

延时
await Task.Delay();
CancellationToken
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            
            //定时两秒取消
            //cts.CancelAfter(2000);
            CancellationToken cToken = cts.Token;
           DownloadAsync3("https://www.baidu.com", 1111,cToken);

            while(Console.ReadLine() != "q")
            {

            }
            cts.Cancel();
            Console.ReadLine();
        }

        static async Task Main1(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            //cts.CancelAfter(2000);
            CancellationToken cToken = cts.Token;
            await DownloadAsync3("https://www.baidu.com", 1111, cToken);

            while (Console.ReadLine() != "q")
            {

            }
            cts.Cancel();
            Console.ReadLine();
        }

        static async Task DownloadAsync(string url,int n)
        {
            using (HttpClient client = new HttpClient())
            {
                for (int i = 0; i < n; i++)
                {
                    string html = await client.GetStringAsync(url);
                    Console.WriteLine($"{DateTime.Now}:{html}");
                }
            }   
        }

        static async Task DownloadAsync2(string url, int n,CancellationToken cancellationToken )
        {
            using (HttpClient client = new HttpClient())
            {
                for (int i = 0; i < n; i++)
                {
                    string html = await client.GetStringAsync(url);
                    Console.WriteLine($"{DateTime.Now}:{html}");
                   

                    #region 请求被取消情况
                    //if(cancellationToken.IsCancellationRequested)
                    //{
                    //    Console.WriteLine("please cancel");
                    //    break;
                    //}

                    cancellationToken.ThrowIfCancellationRequested();
                    #endregion

                }
            }
        }

        /// <summary>
        /// 手动输入q取消
        /// </summary>
        /// <param name="url"></param>
        /// <param name="n"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        static async Task DownloadAsync3(string url, int n, CancellationToken cancellationToken)
        {
            using (HttpClient client = new HttpClient())
            {
                for (int i = 0; i < n; i++)
                {
                   var resp =  await client.GetAsync(url);
                    string html = await resp.Content.ReadAsStringAsync();
                    Console.WriteLine($"{DateTime.Now}:{html}");
                    if(cancellationToken.IsCancellationRequested)
                    {
                        Console.WriteLine("please cancel");
                        break;
                    }

                }
            }
        }
    }
}

LinQ
匿名方法

C# 可以为委托定义匿名方法,名称由编译器内部自动生成。

匿名方法中适用范围仅在其方法体本身,不能跳转。

也不能在匿名方法外部使用的ref和out参数。
在这里插入图片描述
在这里插入图片描述

lambda

是一个匿名函数,是一种高效的类似于函数式编程的表达式
可以搭配委托实现代码的新方式

lambda使用示例
using System;

namespace lambda
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 委托变量不仅可以指向普通方法,也可以指向匿名方法。

            // 无参 Action
            Action f1 = delegate ()
            {
                Console.WriteLine("demo 1 \n ");
            };

            f1();

            // 带参
            Action<int, int> f2 = delegate (int i,int j)
             {
                 Console.WriteLine($"demo 2 {i} {j}  \n ");
             };

            f2(1,2);

            // 带参和返回值 func
            Func<int, int, string> f3 = delegate (int i,int j)
              {
                  return "demo 3 "+(i+j).ToString()+"\n";
              };
            Console.WriteLine(f3(1,2));

            // lambda
            //
            // 省略delete 和数据类型,换成 => (goes to)
            //
            // 因为编译能根据稳妥类型推断参数类型。
            // => 引出方法体
            Func<int, int, string> f4 = (i,j)=>
            {
                return "demo 4 " + (i + j).ToString() + "\n";
            };
            Console.WriteLine(f4(1, 2));

            // 如果委托没有返回值,且方法体只有一行  没有返回值用Action!
            // {}也可以省略
            Action<int, int> f5 = (i, j) => Console.WriteLine("demo 5 " + (i + j).ToString() + "\n") ;
                     f5(1,2);

            // 如果有返回值且只有一行,可以省略{}和return 
            Func<int, int, string> f6 = (i, j) =>
            "demo 6 " + (i + j).ToString() + "\n";

            Console.WriteLine(f6(1, 2));

            // 如果只有一个参数 ()可省略
            Action<int> f7 = (i) => Console.WriteLine("demo 7 " + (i).ToString() + "\n");
            f7(1);

        }
    }
}

Tips

x是studentsSouce集合中的一项
在这里插入图片描述

Linq使用示例
using System;
using System.Collections.Generic;
using System.Linq;

namespace linq
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Linq中提供了很多集合的拓展方法 配合Lambda能简化数据处理
            List<int> list = new List<int>() { 1,3,12,11,3,231,21,32,22};
            #region where
            //where会遍历集合中每个元素,都与每个元素都会调用i=>i>10
            //这个表达式判断是否为true 
            //如果为true,则把这个放到返回的集合中
            //list = list.Where(i=>i > 10).ToList();
            IEnumerable<int>  list2 = MyWhere2(list, i => i > 10);

            foreach (var i in list2)
            {
                Console.WriteLine(i);
            }

            //伪实现
            static List<int> MyWhere1(IEnumerable<int> list, Func<int, bool> f)
            {
                List<int> result = new List<int>();

                foreach (var item in list)
                {
                    if (f(item) == true)
                    {
                        result.Add(item);
                    }
                }
                return result;
            }

            static IEnumerable<int> MyWhere2(IEnumerable<int> list, Func<int, bool> f)
            {
                foreach (var item in list)
                {
                    if (f(item) == true)
                    {
                        //每条数据满足条件立即返回
                        yield return item;
                    }
                }
            }

            // 可以使用var让编译器根据取值进行类型推断 来简化类型的声明
            // var是强类型的 弱类型是dynamic

            // Where方法: 每一项数据都会经过predicate的测试,
            // 如果针对一个元素,predicate执行的返回值为true,那么这个元素就会返到返回值中
            // Where参数是一个lambda表达式的匿名方法,参数e表示当前判断的元素对象,名字随意。

            List<Employee> list3 = new List<Employee>()
           { new Employee(1, "ouou1", 211, true, 1),
             new Employee(2, "ouou2", 2, false, 2),
             new Employee(3, "ouou3", 31, true, 3),
             new Employee(4, "ouou4", 14, false, 4),
              new Employee(4, "ouou4", 11, false, 4),
             new Employee(5, "ouou5", 51, false, 5),
             new Employee(6, "ouou6", 6, true, 6)};

            IEnumerable<Employee> items = list3.Where(list3 => list3.Age > 4);

            foreach (var item in items)
            {
                Console.WriteLine(item);
            }

            #endregion

            // Count():获取数据条数
            int tmp = list3.Count(list3 => list3.Age > 2||list3.Id<3);

            Console.WriteLine(tmp);

            // any():集合中是否至少有一条数据,碰到一条就返回了,效率高
            bool b1 = list3.Where(list3 => list3.Age > 4).Any();
            bool b2 = list3.Any(list3 => list3.Age > 100);
            Console.WriteLine(b1);
            Console.WriteLine(b2);

            // 获取一条数据 没有则报错
            // Single: 有且只有一条满足要求的数据,并将其返回,没有的话报错
            // SingOrDefault: 最多只有一条满足要求的,并将其返回,没有则返回这个类型的默认值object->null int->0,多条的话报错
            // First: 至少有一条,返回第一条
            // FirstOrDefault:返回第一条或者默认值

            //Employee e1 =list3.Single();
            Employee e1 = list3.Where(a=>a.Age>200).Single();
            Employee e2 = list3.Single(a => a.Age > 200);
            Console.WriteLine(e1);
            Console.WriteLine(e2);

            Employee e3 = list3.SingleOrDefault(a => a.Age > 200);

            Employee e4 = list3.First(a => a.Age > 1);
            Console.WriteLine(e4);

            //排序
            //Order() 对数据进行正数排序
            //OrderByDesecending() 倒序排序
            //

            //按年龄排序
            foreach (var item in list3.OrderBy(a => a.Age))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            //按年龄排序 倒序
            foreach (var item in list3.OrderByDescending(a => a.Age))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");
            
            //随机排序
            foreach (var item in list3.OrderByDescending(a => new Random().Next()))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            //按姓名最后一个字符排序
            foreach (var item in list3.OrderByDescending(a =>a.Name[a.Name.Length-1]))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            //多排序 先按第一个规则排序, 然后第一个规则内相同的值再按照第二个规则排序
            foreach (var item in (list3.OrderByDescending(a => a.Name[a.Name.Length - 1])).ThenBy(a=>a.Age))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            // 限制结果集,获取部分数据:
            // Skip(n)跳过n条数据,Take(n)获取n条数据(有多少取多少)

            // 从第二条数据开始获取三条数据

            foreach (var item in list3.Skip(2).Take(3))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");
            // 聚合函数 Max() Min() Average() Sum() Count()
            foreach (var item in list3.Where(a => a.Age > 3 && a.Salary < 8))
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\n");
            Console.WriteLine(list3.Where(a => a.Age > 3 && a.Salary < 8).Min(a=>a.Age));

            // 分组
            // GroupBy() 方法参数是分组条件表达式,返回值为IGrouping<Tkey,TSource>类型的泛型
            // IEnumerable.也就是每一组以一个IGrouping对象的形式返回,IGrouping中key属性这一组分组数据的值
           IEnumerable<IGrouping<long,Employee>> items1= list3.GroupBy(e => e.Id);

            foreach (var item in items1)
            {
                Console.WriteLine(item.Key);
                foreach (var item2 in item)
                {
                    Console.WriteLine(item2);
                }
                Console.WriteLine("***************");
            }
            Console.WriteLine("\n");

            // 投影
            // 把集合汇总的每一项转换为另外一种类型
            foreach (var item in list3.Select(a=>a.Age+","+a.Id))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            // 投影成string类型 IEnumerable<string>
            foreach (var item in list3.Select(a => a.Gender?"男":"女"))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");
            // 投影成Dog类型 IEnumerable<Dog>
            foreach (var item in list3.Select(a => new Dog(a.Id, a.Name)))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");
            // 匿名类型
            var p = new { Name = "tom", Id = 1 };
            Console.WriteLine(p.Name);
            Console.WriteLine("\n");
            // 投影成var类型 新建一个匿名类型
            foreach (var item in list3.Select(a => new { Id=a.Id , Name=a.Name }))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("\n");

            var items4 = list3.GroupBy(a => a.Age).Select(g => new { NianLing = g.Key, MaXS = g.Max(e1 => e1.Salary), RenShu = g.Count() });
            
            foreach (var item in items4)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(new {Max=new int[] { 4, 8, 6 }.Max()});

            string test= "61,90,100,99,18,22,38,66,80,93,55,50,89";

            double a = 0;

            string[] test2 = test.Split(",");

            //foreach (var item in test2)
            //{
            //   a+= int.Parse(item);
            //}
            
            //a/=test2.Count();

            Console.WriteLine(test2.Select(a => int.Parse(a)).Average());

            string s = "hello wer,.ssdfQWerQQ";

            var vars = s.Where(c => char.IsLetter(c)).Select(c => char.ToLower(c)).GroupBy(c => c).Select(c => new { c.Key, Count = c.Count() });

            foreach (var item in vars)
            {
                Console.WriteLine(item);
            }
        } 
}
}

yield 关键字 是一个迭代器 相当于实现了IEnumerator

实现IEunmerable接口,实现遍历效果
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linq实现
{
    /// <summary>
    /// IEnumerable 类型 -- 可迭代类型
    /// IEnumerator 枚举器
    /// Enum 枚举
    /// 只要一个类型实现了IEunmerable接口,就可以遍历
    /// </summary>
    public class IEnumerableShow
    {
        public void Show()
        {
            int[] array = { 1, 2, 3, 4, 5, 6 };
            Student student = new Student { Id=1};

            foreach (var i in student)
            {
                Console.WriteLine(i);
            }
        }


        /// <summary>
        /// 让Student 可遍历
        /// 实现接口 IEnumerable
        /// 只有一个方法
        /// yield 关键字 
        /// </summary>
        class Student:IEnumerable
        {
            public int Id { get; set; }

            public IEnumerator GetEnumerator()
            {
                //yield return "OU1";
                //yield return "OU2";
                //yield return "OU3";
                string[] student = { "111", "222", "333" };
                return new StudentEnumerator(student);
            }
        }
    }

    internal class StudentEnumerator : IEnumerator
    {
        string[] _student;

        int _position = -1;
        public StudentEnumerator(string[] student)
        {
            this._student = student;
        }

        public object Current 
        {
            get
            {
                if(_position == -1)
                {
                    throw new InvalidOperationException();
                }
                if(_position>=_student.Length)
                {
                    throw new InvalidOperationException();
                }
                return _student[_position];

            }
        }

        public bool MoveNext()
        {
            if(_position<_student.Length-1)
            {
                _position++;
                return true;
            }
            else
            {
                return false;
            }
        }

        public void Reset()
        {
            _position = -1;
        }
    }
}

Linq Where实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linq实现
{
    /// <summary>
    /// Linq to object (数组、list集合) --内存里面的数据
    /// </summary>
    public static class LinqShow
    {
       
        public static void Show()
        {
            //List<Students> students = new List<Students>();
            //foreach (var item in studentsSource)
            //{
            //    if(item.Id == 2)
            //    {
            //        students.Add(item);
            //    }
            //}
        }

        //Func<Students, bool> func = test;

        public static  List<Students> MyWhere(this List<Students>  resource,Func<Students, bool> func)
        {
            List<Students> students = new List<Students>();
            foreach (var item in resource)
            {
                // 看成返回值是bool类型的方法
                //if (item.Id == 2)
                //{
                //    students.Add(item);
                //}

                if (func.Invoke(item))
                {
                    students.Add(item);
                }
            }
            return students;
        }

        public static bool test(Students students)
        {
            return students.Id < 20;
        }
    } 

    public static class LinqExtend
    {
        public static IEnumerable<TSource> MyWhere2<TSource>(this IEnumerable<TSource> resource, Func<TSource, bool> func)
        {
            List<TSource> students = new List<TSource>();
            foreach (var item in resource)
            {
                // 看成返回值是bool类型的方法
                //if (item.Id == 2)
                //{
                //    students.Add(item);
                //}

                if (func.Invoke(item))
                {
                    students.Add(item);
                }
            }
            return students;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ou.cs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值