C#学习-刘铁猛

news2024/9/17 7:40:31

文章目录

    • 1.委托
      • 委托的具体使用-魔板方法
      • 回调方法【好莱坞方法】:通过委托类型的参数,传入主调方法的被调用方法,主调方法可以根据自己的逻辑决定调用这个方法还是不调用这个方法。【演员只用接听电话,如果通过,导演会打电话通知演员。】
      • 同步调用
      • 同步方法;使用委托对三个方法进行间接调用
      • 多播委托,也是同步
      • 使用Thread进行显示异步调用
      • 使用Task进行显式异步调用
      • 使用接口来取代委托
      • C# 中提供的委托,Action和Func
      • P30lambda表达式
      • P29接口,反射,隔离,依赖注入

视频连接

1.委托

委托方法要和委托签名相匹配

// See https://aka.ms/new-console-template for more information
using ConsoleApp1.Model;

namespace ConsoleApp1
{
    public class Program1
    {
        static void Main(string[] args) {
            Calculator calculator = new Calculator();
            calculator.Report();//直接调用
            //Action委托
            Action action = new Action(calculator.Report);
            action.Invoke(); //使用委托进行间接调用
            //Function委托
            Func<double, double, double> func1 = new Func<double, double, double>(calculator.Add);
            Func<double, double, double> func2 = new Func<double, double, double>(calculator.Sud);
            double x = 200;
            double y = 100;
            double z = 0;
            z=func1.Invoke(x,y);
            Console.WriteLine(z);
            z = func2.Invoke(x, y);
            Console.WriteLine(z);

        }
    }
}

自定义委托方法Calc

// See https://aka.ms/new-console-template for more information
using ConsoleApp1.Model;

namespace ConsoleApp1
{
    public delegate double Calc(double x, double y);
    public class Program
    {
        static void Main(string[] args) {
            Calculator calculator = new Calculator();
            //委托的具体方法需要与委托的签名相匹配
            Calc calc1 = new Calc(calculator.Add);
            Calc calc2 = new Calc(calculator.Sud);
            double x = 1.12;
            double y = 2.23;
            double res1=calc1(x,y);
            double res2 = calc2(x, y);
            Console.WriteLine(res1);
            Console.WriteLine(res2);

        }
    }
}

在这里插入图片描述

委托的具体使用-魔板方法

// See https://aka.ms/new-console-template for more information
using ConsoleApp1.Model;

namespace ConsoleApp1
{
    
    public class Program
    {
        static void Main(string[] args) {
            Productfactory productfactory = new Productfactory();
            WrapFactory wrapFactory = new WrapFactory();
            //创建委托实例
            Func<Product> func1 = new Func<Product>(productfactory.MakePizza);
            Func<Product> func2 = new Func<Product>(productfactory.MakeToyCar);
            Box box1 = wrapFactory.WrapProduct(func1);
            Box box2 = wrapFactory.WrapProduct(func2);

            Console.WriteLine(box1.Product.Name);
            Console.WriteLine(box2.Product.Name);

        }
    }
    class Product {
        public string Name{get;set;}
    }
    class Box
    {
        public Product Product { get; set; }
    }
    class WrapFactory {
    //魔板方法,大部分逻辑已经固定
        public Box WrapProduct(Func<Product> getProduct) {
        Box box = new Box();
        Product product= getProduct.Invoke();
        box.Product = product;
        return box;
        }
    }
    class Productfactory {
        public Product MakePizza() { 
            Product product = new Product();
            product.Name = "pizza";
            return product;
        }
        public Product MakeToyCar()
        {
            Product product = new Product();
            product.Name = "Toy Car";
            return product;
        }
    }
}


回调方法【好莱坞方法】:通过委托类型的参数,传入主调方法的被调用方法,主调方法可以根据自己的逻辑决定调用这个方法还是不调用这个方法。【演员只用接听电话,如果通过,导演会打电话通知演员。】

// See https://aka.ms/new-console-template for more information
using ConsoleApp1.Model;

namespace ConsoleApp1
{
    
    public class Program
    {
        static void Main(string[] args) {
            Productfactory productfactory = new Productfactory();
            WrapFactory wrapFactory = new WrapFactory();
            //创建委托实例
            Func<Product> func1 = new Func<Product>(productfactory.MakePizza);
            Func<Product> func2 = new Func<Product>(productfactory.MakeToyCar);
            //创建委托实例
            Logger logger = new Logger();   
            Action<Product> log = new Action<Product>(logger.Log);
            Box box1 = wrapFactory.WrapProduct(func1, log);
            Box box2 = wrapFactory.WrapProduct(func2, log);

            Console.WriteLine(box1.Product.Name);
            Console.WriteLine(box2.Product.Name);

        }
    }
    class Logger {
        public void Log(Product product) {
            Console.WriteLine("Product'{0}' is created at{1},price is '{2}'", product.Name,DateTime.UtcNow,product.Price);//不带时区的时间
        }
    }
    class Product {
        public string Name{get;set;}
        public double Price{get;set;} 
    }
    class Box
    {
        public Product Product { get; set; }
    }
    class WrapFactory {

        public Box WrapProduct(Func<Product> getProduct,Action<Product> logCallback) {
        Box box = new Box();
        Product product= getProduct.Invoke();
            if (product.Price>50) {
                logCallback(product);
            }
        box.Product = product;
        return box;
        }
    }
    class Productfactory {
        public Product MakePizza() { 
            Product product = new Product();
            product.Name = "pizza";
            product.Price = 20;
            return product;
        }
        public Product MakeToyCar()
        {
            Product product = new Product();
            product.Name = "Toy Car";
            product.Price =100;
            return product;
        }
    }
}


在这里插入图片描述

同步调用

// See https://aka.ms/new-console-template for more information
using ConsoleApp1.Model;
using System.ComponentModel;

namespace ConsoleApp1
{

    public class Program
    {
        static void Main(string[] args)
        {
            Student1 student1 = new Student1() {ID=1,PenColor=ConsoleColor.Yellow };
            Student1 student2 = new Student1() { ID =2, PenColor = ConsoleColor.Blue };
            Student1 student3 = new Student1() { ID =3, PenColor = ConsoleColor.Green };

            student1.DoWork();
            student2.DoWork();
            student3.DoWork();
            for (int i=0;i<10 ;i++) {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Main thread is working {0} hour.",i);
                Thread.Sleep(1000); 
            }
        }
    }
    class Student1 {
        public string Name { get; set; }
        public int ID { get; set; }
        public ConsoleColor PenColor { get; set; }
        public void DoWork() {
            for (int i = 0; i < 4; i++)
            {
                Console.ForegroundColor = PenColor;
                Console.WriteLine("ID is {0} thread is working----{1}hour.", ID,i);
                Thread.Sleep(1000);
            }

        }
    }

}


同步方法;使用委托对三个方法进行间接调用

            Student1 student1 = new Student1() {ID=1,PenColor=ConsoleColor.Yellow };
            Student1 student2 = new Student1() { ID =2, PenColor = ConsoleColor.Blue };
            Student1 student3 = new Student1() { ID =3, PenColor = ConsoleColor.Green };
            Action action1 = new Action(student1.DoWork);
            Action action2 = new Action(student2.DoWork);
            Action action3 = new Action(student3.DoWork);
            action1.Invoke();
            action2.Invoke();
            action3.Invoke();

多播委托,也是同步

            Action action1 = new Action(student1.DoWork);
            Action action2 = new Action(student2.DoWork);
            Action action3 = new Action(student3.DoWork);
            action1+=action2;
            action1+=action3;
            action1.Invoke();

委托-使用委托可以进行隐式的异步调用。

使用Task.Run(() => action1.Invoke());代替原来的BeginInvoke方法。

// See https://aka.ms/new-console-template for more information
using ConsoleApp1.Model;
using System.ComponentModel;

namespace ConsoleApp1
{

    public class Program
    {
        static void Main(string[] args)
        {
            Student1 student1 = new Student1() {ID=1,PenColor=ConsoleColor.Yellow };
            Student1 student2 = new Student1() { ID =2, PenColor = ConsoleColor.Blue };
            Student1 student3 = new Student1() { ID =3, PenColor = ConsoleColor.Green };
            Action action1 = new Action(student1.DoWork);
            Action action2 = new Action(student2.DoWork);
            Action action3 = new Action(student3.DoWork);
            //action1.BeginInvoke(null,null);
        
            var task1=Task.Run(() => action1.Invoke());
          //  Console.WriteLine($"task1-action1------>{task1}");
            var task2 = Task.Run(() => action2.Invoke());
           // Console.WriteLine($"task2-action2----->{task2}");
            var task3 = Task.Run(() => action3.Invoke());
          //  Console.WriteLine($"task3-action3----->{task3}");
            for (int i=0;i<10 ;i++) {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Main thread is working {0} hour.",i);
                Thread.Sleep(1000); 
            }
        }
    }
    class Student1 {
        public string Name { get; set; }
        public int ID { get; set; }
        public ConsoleColor PenColor { get; set; }
        public void DoWork() {
            for (int i = 0; i < 4; i++)
            {
                Console.ForegroundColor = PenColor;
                Console.WriteLine("Student  {0} thread is working----{1}hour.", ID,i);
                Thread.Sleep(1000);
            }

        }
    }

}


使用Thread进行显示异步调用

在这里插入图片描述

        static void Main(string[] args)
        {
            Student1 student1 = new Student1() {ID=1,PenColor=ConsoleColor.Yellow };
            Student1 student2 = new Student1() { ID =2, PenColor = ConsoleColor.Blue };
            Student1 student3 = new Student1() { ID =3, PenColor = ConsoleColor.Green };

            //使用Thread进行显示异步调用
            Thread t1 = new Thread(new ThreadStart(student1.DoWork));
            Thread t2 = new Thread(new ThreadStart(student2.DoWork));
            Thread t3 = new Thread(new ThreadStart(student3.DoWork));
            t1.Start();
            t2.Start(); 
            t3.Start();

            for (int i=0;i<10 ;i++) {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Main thread is working {0} hour.",i);
                Thread.Sleep(1000); 
            }
        }

使用Task进行显式异步调用

在这里插入图片描述
在这里插入图片描述

            //使用Task行显示异步调用
            Task task1 = new Task(new Action(student1.DoWork));
            Task task2 = new Task(new Action(student2.DoWork));
            Task task3 = new Task(new Action(student3.DoWork));
            task1.Start();
            task2.Start();  
            task3.Start();

主线程和分支线程,互不等待,发生资源上的争抢。

使用接口来取代委托

// See https://aka.ms/new-console-template for more information
using ConsoleApp1.Model;
using System.ComponentModel;

namespace ConsoleApp1
{
    //用接口代替委托
    public class Program
    {
        static void Main(string[] args)
        {
            IProductfactory Pizzafactory = new Pizzafactory();
            IProductfactory Toycarfactory = new ToyCarfactory();
            //包装工厂生产盒子
            WrapFactory wrapFactory = new WrapFactory();
            Box pizzaBox=wrapFactory.WrapProduct(Pizzafactory);
            Box totcarBox = wrapFactory.WrapProduct(Toycarfactory);
            Console.WriteLine(pizzaBox.Product.Name);
            Console.WriteLine(totcarBox.Product.Name);

        }
    }
    interface IProductfactory {
        Product Make();
    }

    class Pizzafactory : IProductfactory
    {
        public Product Make(){
            Product product = new Product();
            product.Name = "pizza";
            return product;
        }
    }
    class ToyCarfactory : IProductfactory
    {
        public Product Make()
        {
            Product product = new Product();
            product.Name = "Toy Car";

            return product;
        }
    }
    //上面是新定义的两个工厂ToyCarfactory 和Pizzafactory 
    class Product
    {
        public string Name { get; set; }
        public double Price { get; set; }
    }
    class Box
    {
        public Product Product { get; set; }
    }
    class WrapFactory
    {

        public Box WrapProduct(IProductfactory productfactory)//不需要委托类型的参数,工厂类型的参数即可
        {
            Box box = new Box();
            Product product = productfactory.Make();
          
            box.Product = product;
            return box;
        }
    }
    //下面的这个class Productfactory可以不不需要了
    class Productfactory
    {
        public Product MakePizza()
        {
            Product product = new Product();
            product.Name = "pizza";
            product.Price = 20;
            return product;
        }
        public Product MakeToyCar()
        {
            Product product = new Product();
            product.Name = "Toy Car";
            product.Price = 100;
            return product;
        }
    }
}


在这里插入图片描述

C# 中提供的委托,Action和Func

Action适用于没有返回值的委托,Func适用于有返回值的委托。
可以使用var关键字缩短代码
用var action=new Action<string,int>(SayHello);代替Action<string,int> action=new Action<string,int>(SayHello);
Func适用于有返回值的委托

static void Main(string[] args){
	Func<int,int,int> myFunc=new Func<int,int,int>(Add);
	int res =myFunc(4,5);
	Console.WriteLine(res);
}

static int Add(int a,int b){
	return a+b;
}
}

Action适用于没有返回值的委托,

static void Main(string[] args){
	Action action=new Action<string,int>(SayHello);
	action("Tim",3);
}

static void SayHello(string name,int round){
	for(int i=0;i<round;i++){
	Console.WriteLine($"Helo {name}!");
}
}

P30lambda表达式

(int a, int b) => { return a + b; }

        static void Main(string[] args)
        {
            //lambda表达式,匿名的
           // Func<int, int, int> func = new Func<int, int, int>((int a, int b) => { return a + b; });
            //lambda表达式,委托时简写
           Func<int, int, int> func = (int a, int b) => { return a + b; };
            int res=func(1, 2);
            Console.WriteLine(res);
            func = new Func<int, int, int>((int a, int b) => { return a *b; });
            int res2 = func(1, 2);
            Console.WriteLine(res2);

        }

//lambda表达式,委托时简写,把lambda表达式赋值给委托类型的变量。
Func<int, int, int> func = (int a, int b) => { return a + b; };
泛型委托的类型推断

   public class Program
   {
       static void Main(string[] args)
       {
           DoSomeCalc((a, b) => { return a + b; },1,2);
           Console.WriteLine("handle result!");

       }
       static void DoSomeCalc<T>(Func<T,T,T>func,T x,T y) {
           T res=  func(x, y);
           Console.WriteLine(res);
       }
   }

P29接口,反射,隔离,依赖注入

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1939613.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

刷题笔记 739. 每日温度 (单调栈),215. 数组中的第K个最大元素(堆),347.前 K 个高频元素

739. 每日温度 &#xff08;单调栈&#xff09;. - 备战技术面试&#xff1f;力扣提供海量技术面试资源&#xff0c;帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/daily-temperatures/description/?envTypestudy-plan-v2&envI…

Fast Planner规划算法(一)—— Fast Planner前端

本系列文章用于回顾学习记录Fast-Planner规划算法的相关内容&#xff0c;【本系列博客写于2023年9月&#xff0c;共包含四篇文章&#xff0c;现在进行补发第一篇&#xff0c;其余几篇文章将在近期补发】 一、Fast Planner前端 Fast Planner的轨迹规划部分一共分为三个模块&…

Haproxy服务

目录 一.haproxy介绍 1.主要特点和功能 2.haproxy 调度算法 3.haproxy 与nginx 和lvs的区别 二.安装 haproxy 服务 1. yum安装 2.第三方rpm 安装 3.编译安装haproxy 三.配置文件详解 1.官方地址配置文件官方帮助文档 2.HAProxy 的配置文件haproxy.cfg由两大部分组成&…

React+TypeScript 组件库开发全攻略:集成Storybook可视化与Jest测试,一键发布至npm

平时我除了业务需求&#xff0c;偶尔会投入到UI组件的开发中&#xff0c;大多数时候只会负责自己业务场景相关或者一小部分公共组件&#xff0c;极少有从创建项目、集成可视化、测试到发布的整个过程的操作&#xff0c;这篇文章就是记录组件开发全流程&#xff0c;UI组件在此仅…

RabbitMQ学习实践二:MQ的实现

文章是本人在学习springboot实现消息队列功能时所经历的过程的记录&#xff0c;仅供参考&#xff0c;如有侵权请随时指出。 参考文章地址&#xff1a; RabbitMQ安装与入门_rabbitmq win11配置-CSDN博客 RabbitMQ入门到实战一篇文章就够了-CSDN博客 RabbitMQ系列&#xff08…

AI跟踪报道第48期-新加坡内哥谈技术-本周AI新闻:Open AI 和 Mistral的小型模型

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…

华为路由器SSH登录实验

概念 SSH全称安全外壳&#xff08;Secure Shell&#xff09;协议&#xff0c;这个协议的目的就是为了取代缺乏机密性保障的远程管理协议&#xff0c;SSH基于TCP协议的加密通道&#xff0c;让客户端使用服务器的RSA公钥来验证SSHv2服务器的身份。 创建密钥对 在充当SSH服务器的…

UE4-获得角色控制权的两种方法

方法一&#xff1a; 方法二&#xff1a; 注意此方法不能有多个玩家出生点&#xff0c;如果有多个玩家出生点&#xff0c;会随机的选择一个玩家出生点进行生成。

C++的map和set介绍

系列文章目录 二叉树搜索树 map和set习题 文章目录 系列文章目录前言一、关联式容器键值对二、树形结构的关联式容器2.1 set2.1.1 set的介绍2.1.3 set的使用删除节点find的不同效率count举例lower_bound 和 upper_bound 2.2 multiset2.2.1 区别&#xff1a;find查找erase删除e…

Deepin系统,中盛科技温湿度模块读温度纯c程序(备份)

#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <termios.h>int main() {int fd;struct termios options;// 打开串口设备fd open("/dev/ttyMP0", O_RDWR | O_NOCTTY|O_NDELAY); //O_NDELAY:打开设备不阻塞//O_NOCTT…

http请求网址或网页的全流程

客户端通过浏览器请求网址或网页资源的步骤如下&#xff1a; http请求网址或网页的全流程 1.首先&#xff0c;浏览器做的第一步就是解析 URL 得到里面的参数2.浏览器封装 HTTP 请求报文3.DNS 域名解析获取 IP 地址4. 建立 TCP 连接5.浏览器发送请求6.负责传输的 IP 协议7.使用 …

基于Llama Index构建RAG应用(Datawhale AI 夏令营)

前言 Hello&#xff0c;大家好&#xff0c;我是GISer Liu&#x1f601;&#xff0c;一名热爱AI技术的GIS开发者&#xff0c;本文参与活动是2024 DataWhale AI夏令营&#xff1b;&#x1f632; 在本文中作者将通过&#xff1a; Gradio、Streamlit和LlamaIndex介绍 LlamaIndex 构…

【初阶数据结构】5.栈和队列

文章目录 1.栈1.1 概念与结构1.2 栈的实现2.队列2.1 概念与结构2.2 队列的实现3.栈和队列算法题3.1 有效的括号3.2 用队列实现栈3.3 用栈实现队列3.4 设计循环队列 1.栈 1.1 概念与结构 栈&#xff1a;一种特殊的线性表&#xff0c;其只允许在固定的一端进行插入和删除元素操…

从零开始实现大语言模型(八):Layer Normalization

1. 前言 Layer Normalization是深度学习实践中已经被证明非常有效的一种解决梯度消失或梯度爆炸问题,以提升神经网络训练效率及稳定性的方法。OpenAI的GPT系列大语言模型使用Layer Normalization对多头注意力模块,前馈神经网络模块以及最后的输出层的输入张量做变换,使shap…

android13 默认输入法配置分析rom默认配置修改分析

总纲 android13 rom 开发总纲说明 目录 1.前言 2.解决方法 3.方法分析 3.1方法1 3.2方法2 4.彩蛋 1.前言 Android13上需要预装中文输入法, 但是直接预装输入法的话,会出现默认使能的问题,点击TextEdit输入框, 弹出的是默认英文输入法LatinIME, 而不是谷歌拼音输入…

解决GoLand添加GOROOT提示The selected directory is not a valid home for Go Sdk的问题

现象 解决 在Go安装路径下找到zversion.go文件&#xff0c;我的在D:\Program Files\Go1.21.1\src\runtime\internal\sys下面 打开文件&#xff0c;添加如下内容&#xff1a; const TheVersion go1.21.1保存后再重新添加GOROOT即可

2024 杭电多校第一场

目录 目录 树 博弈 传送 树 给一棵根为 1 的有根树&#xff0c;点 i 具有一个权值 Ai 。 定义一个点对的值 f(u,v)max(Au,Av)|Au−Av| 。 你需要对于每个节点 i &#xff0c;计算 ansi∑u∈subtree(i),v∈subtree(i)f(u,v) &#xff0c;其中 subtree(i) 表示 i 的子树。 请…

如何让LabVIEW程序框图的图标简化,从而节省空间?

再点击选项 取消掉箭头所示的√即可。 这样就可以将生成的图标从下面所示&#xff1a; 变成简化的图标&#xff0c;如下所示&#xff1a;

UML的六大关系---泛化、实现、关联、聚合、组合、依赖

文章目录 前言1. 泛化关系(Generalization)2. 实现关系(Realization)3. ‌关联关系(Association)4. 聚合关系(Aggregation)5. 组合关系(Composition)6. 依赖关系(Dependency)总结 前言 讲到设计模式&#xff0c;就会有 U M L UML UML类图这个东西。 一开始就很难理解各种线啥意…

【Spring Boot】网页五子棋项目中遇到的困难及解决方法

目录 一、HikariPool-1 - Starting异常二、Invalid bound statement (not found)异常三、The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary异常四、The server time zone value时区报错异常五、补充知识点…