C# 객체 지향 (5)

맡기다

일반위탁

약간의 이해

Calculator 클래스의 멤버 함수를 변수에 저장하는 방법 int(데이터 유형) num=12, Calculator(데이터 유형) method=method;

대리자는 메서드를 저장하는 데 사용되는 메서드의 형식을 정의하는 클래스입니다.

구문: 액세스 한정자 대리자 반환 값, 유형 대리자 이름(매개 변수 목록), 액세스 한정자가 선언되지 않은 경우 기본값은 public입니다.

관행

 //定义计算机类
    class Calculator
    {//无返回值无参数
        public void Report()
        {
            Console.WriteLine("No report");
        }
        public int Abs(int v)
        {
            return Math.Abs(v);//0<=x<=value
        }
    }
    //定义无返回值无参数的委托
    public delegate void NoRetParFun();
    //定义有返回值有参数的委托
    public delegate int RetParfun(int v);
    internal class Program
    {
        //定义一个无返回值无参数的函数
        public static void Print()
        {
            Console.WriteLine("program.print");
        }
        static void Main(string[] args)
        {
            Calculator calculator = new Calculator();
            //创建无返回值的委托类型对象
            NoRetParFun noRetParFun01 = new NoRetParFun(calculator.Report);//把计算机类里的report方法传入noretparfun01里面
            //调用方式一
            noRetParFun01();
            //创建委托类型对象
            NoRetParFun noRetParFun02=calculator.Report;//把计算机类里的report方法传入noretparfun02里面
            //调用方法二
            noRetParFun02.Invoke();
            //创建有返回值的委托类型
            RetParfun retparfun =calculator.Abs;
            Console.WriteLine(retparfun(-10));//10
            Console.WriteLine(retparfun.Invoke(-20));//20
            Console.WriteLine("-----");
            //应用,可以进行函数的运算
            noRetParFun01 += Print;
            noRetParFun01();
            Console.WriteLine("----");
            noRetParFun01 -= calculator.Report;
            noRetParFun01.Invoke();
            //验证委托是一个;类
            Console.WriteLine("------");
            Console.WriteLine(typeof(Calculator).IsClass);//true
            Console.WriteLine(typeof(int).IsClass);//false
            Console.WriteLine(typeof(NoRetParFun).IsClass);//true
            Console.WriteLine(typeof(RetParfun).IsClass);//true
            Console.ReadKey();

시스템 위임

행동

  //无返回值无参数
        public static void Print() {
            Console.WriteLine("print.");
        }
        //无返回值,有参数
        public static void Say(string name)
        {
            Console.WriteLine($"{name}-");
        }
 //系统委托就是系统定义好的委托,可以直接使用
            //action系统委托是没有返回值可以有参数列表的委托
            //public delegate void Action();
            //public delegate void Action<in T>(T obj);
            Action action01 = Print;
            action01();
            Action<string> action02 = Say;
            action02.Invoke("peter");

기능

     //有返回值,无参数
        public static string Hellow()
        {
            return "hellow";
        }
        //有返回值有参数
        public static string Join(bool b,int num)
        {
            return b + "-" + num;
        }
//Func系统委托是有参数有返回值的委托
            //public delegate Tresult Func<out Tresult>();
            //public delegate Tresult func<in T1,in  T2,out Tresult>(T1 arg1,T2 srg2);
            Func<string> func = Hellow;
            //只是返回值,需要打印,所以。。。
            Console.WriteLine(func());
            Func<bool,int,string> func01=Join;
            Console.WriteLine(func01.Invoke(false,1));

이벤트

약간의 이해

이벤트는 안전한 위임 패키지인 위임을 기반으로 합니다.단순히 보다 안전한 이벤트 위임으로 이해됩니다.

구문: 액세스 한정자 이벤트 대리자 유형 이벤트 이름;

특징: 이벤트의 초기화는 이벤트를 정의한 클래스에서, 이벤트의 호출은 이벤트를 정의한 클래스에서 수행해야 하며, +=, -= 연산은 다른 클래스에서 수행할 수 있습니다.

관행

   class Text {
        //普通委托字段
        public Action action01;
        //事件(安全委托)
        public event Action action02 = Program.Print;
        public void CallEvent()
        {
            action02();
        }
    }
    internal class Program
    {
        public static void Print()
        {
            Console.WriteLine("program.print");
        }
        public static void Show()
        {
            Console.WriteLine("program.show");
        }
        static void Main(string[] args)
        {
            Text text = new Text();
            //普通委托
            text.action01 = Print;
            text.action01();
            //事件
            Text text2 = new Text();
            //报错只能进行+=,事件不能在其他类中进行初始化
            /*text2.action02 = Print*/;
            //报错只能进行+=,事件不能在其他类中进行调用
            //text2.action02();
            //只能通过定义事件类中的函数进行事件的间接调用
            text2.CallEvent();
            Console.WriteLine("------");
            text2.action02 += Show;
            text2.CallEvent();
            text2.action02 -= Show;
            text2.CallEvent();
            Console.ReadKey();

익명 기능

약간의 이해

정의: 익명 함수는 이름이 없는 함수로 주로 델리게이트 및 이벤트와 함께 사용되며 델리게이트 및 이벤트가 없는 익명 함수는 의미가 없습니다.

기능: 익명 함수를 정의하는 주요 기능은 할당을 수행하는 것입니다.

관행

  //一个普通委托调用
        public static Action action = Print;
        public static void Print()
        {
            Console.WriteLine("print");
        }
        static void Main(string[] args)
        {
            action();
            Console.ReadKey();
  //匿名函数的
        public static Action action = delegate(){
            Console.WriteLine("匿名的");
            };
      
        static void Main(string[] args)
        {
            action();
            Console.ReadKey();
        }
 //定义一个action委托参数列表,用匿名函数
        public static Action<string, int> GetAction = delegate (string s, int num)
        {
            Console.WriteLine($"{ s}-{num}-");
        };
      
        static void Main(string[] args)
        {
            GetAction("peter", 12);
            Console.ReadKey();
  //定义一个事件,用匿名函数
        public static event Func<int, string> func = delegate (int num)
        {
            return num + "";
        };
        static void Main(string[] args)
        {

            Console.WriteLine(func(12));
            //查看类型
            Console.WriteLine(func(12).GetType());
            Console.ReadKey();
   //匿名函数还可以进行参数传参
 public static void Test(Action action)
        {
            action();
        }
        static void Main(string[] args)
        {
            Test(delegate ()
            {
                Console.WriteLine("匿名函数还可以进行参数传参");
            });


람다 식

약간의 이해

람다 식은 익명 함수의 정의를 단순화하는 데 사용되는 식 유형입니다.

역할: 익명 표현 함수의 정의 단순화

구문: (매개변수 목록) => 함수 본문 {}

요점: 함수 본문에 하나의 문만 있고 {} 생략 가능 함수에 하나의 문만 있고 반환 문인 경우 {}와 반환 모두 생략 가능, 속성.

관행

//属性的时候
private string name;
public string Name{get=>name;set=>name=value;}
//
 Test(()=> Console.WriteLine("匿名函数还可以进行参数传参"));
//
 public static event Func<int, string> func =(int num)=>num + "";

멀티스레딩

약간의 이해

멀티스레딩은 프로그램이 동시에 다른 비즈니스 로직을 실행할 수 있도록 프로그램에 대한 여러 실행 경로를 여는 것입니다.

구문: Thread 클래스 객체(객체) 생성, 비즈니스 로직 함수(경로에서 실행할 비즈니스 로직), 스레드 시작

관행

   //创建线程对象1
            Thread thread = new Thread(LiFile);
            thread.Start();

            //创建线程对象2
            Thread thread01 = new Thread(FilFile);
            thread01.Start();
            //主线程
            int second = 20;
            string name = "主线程";
            while (true)
            {
                Thread.Sleep(1 * 1000);
                Console.WriteLine($"{name}-{second--}--");
                if (second == 0)
                {
                    Console.WriteLine("主线程结束喽");
                    return;
                }
            }
            
        }
        //扫描文件线程
        public static void LiFile() {
            int second = 15;
            string name = "文件喽";
        while (true)
            {
                Thread.Sleep(1*1000);
                Console.WriteLine($"{name}-扫描开始了-{second--}");
                if (second == 0) {
                    Console.WriteLine($"扫描停止了{name}");
                    return;
                }
            }
        }
        public static void FilFile()
        {
            int second = 10;
            string name = "fil文件喽";
            while (true)
            {
                Thread.Sleep(1 * 1000);
                Console.WriteLine($"{name}-扫描开始了-{second--}");
                if (second == 0)
                {
                    Console.WriteLine($"扫描停止了{name}");
                    return;
                }
            }
        }
      }
}

반복자

약간의 이해

IEnumerator 인터페이스는 foreach를 사용하여 컨테이너를 반복하는 데 사용할 수 있는 관련 메서드를 주로 제공하는 반복자입니다. IEnumerable 이 인터페이스는 주로 외부에서 사용할 수 있는 반복자에 사용됩니다.

관행

//首先定义一个集合类用foreach进行迭代
    class CustomArray<T>: IEnumerable,IEnumerator//IEnumerable报错?需要导入using System.Collections;再导入接口
    {
        private T[] array;//想要存储任意数据类型,改用什么,泛型
        public CustomArray(T[] array)
        {
            this.array = array;
        }
        //定义一个索引值
        public int index = -1;
        //IEnumerator提供的用于返回当前数据的属性
        object IEnumerator.Current =>this.array[index];//lambda表达式

        //IEnumerable提供的可以用于返回迭代器的方法
        public IEnumerator GetEnumerator()
        {
            return this;
        }
        //IEnumerator提供的用于移动索引的方法
        bool IEnumerator.MoveNext()
        {
            index++;
            return this.index < this.array.Length;

        }
        //IEnumerator提供的用于复位索引的方法
        void IEnumerator.Reset()
        {
            this.index = -1;
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            CustomArray<int> customArray=new CustomArray<int>(new int[] { 1, 2, 3 ,4});
            foreach (int item in customArray)//报错?不包含GetEnumerator的公共实例或扩展定义
            {
                Console.WriteLine(item);  
            }
            CustomArray<string> customArray01 = new CustomArray<string>(new string[] { "a", "b", "c", "d" });
            foreach (string item in customArray01)//报错?不包含GetEnumerator的公共实例或扩展定义
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
//步骤,太多,简化一些
//不使用IEnumerator接口
   public IEnumerator GetEnumerator()
        {
            //直接写for循环
            for (int i = 0; i < this.array.Length; i++)
            {
               yield return this.array[i];//这是就需要yield
            }
        }
//自己定义了一个类里面的方法,只不过和IEnumerable同名的方法
 public IEnumerator GetEnumerator()
        {
            //直接写for循环
            for (int i = 0; i < this.array.Length; i++)
            {
               yield return this.array[i];//这是就需要yield
            }
        }

보다


~였다

관행

//该数据类型定义的变量可以存储任何类型的数据
int[] nums=new int[]{2,3,4,5}
foreach(var item in nums){
Console.WriteLine(item);}
//var?
var data="peer";
Console.WriteLine(data is string);
//一旦赋值就不能在赋值其他数据类型的值
//var只能修饰局部变量不能修饰成员变量;

튜플

관행

  //元组就是计算机用于存储数据的一种简化格式
            //语法:(数据类型 字段名,数据类型 字段名。。。) 元组名=(值,值)
            (double a, int b) t1 = (12.3, 2);
            Console.WriteLine($"a={t1.a},b={t1.b}");
            //定义一个匿名数组,那么怎么显示值呢
            (string, int) t2 = ("peter", 29);
            Console.WriteLine($"{t2.Item1}-{t2.Item2}");//important
            //定义一些其他格式呢
            var t3 = (ID: 11, Name: "jack", Data: 12);
            Console.WriteLine($"id={t3.ID},naem={t3.Name},data={t3.Data}");
            //匿名元组
            var t4 = (11, "lucky", 14);
            Console.WriteLine($"id:{t4.Item1},name={t4.Item2},data={t4.Item3}");
            Console.WriteLine(MinAndMax<int>(new int[] { 1, 2, 20, 10 }));
            Console.WriteLine(MinAndMax<int>(new int[] { 1, 11, 22 }).Min);
            Console.WriteLine(MinAndMax<int>(new int[] { 1, 11, 22 }).Max);

            //元组是值类型还是引用类型
            (int,int) a=(1,11);
            (short,short) b=(1,11);
            Console.WriteLine(a == b);
            Console.WriteLine(b != a);
            var c = b;
            c = (20, 11);
            Console.WriteLine(c);
            Console.WriteLine(b);
            Console.ReadKey();
        }
        //定义一个函数返回数组中的最小值和最大值(1,10)
        public static (double Min,double Max) MinAndMax<T>(T[] array)
        {
            return (Min: 10, Max: 20);
        }
    }

{}그리고?

관행

  class Player {
            public int id;
            public string name;
        }
       
        static void Main(string[] args)
        {
            //{}可以用来初始化对象
            //数组的形式
            int[] nums = { 1, 2, 3, 4, 5, };
            Console.WriteLine(nums[1]);
            //集合的形式
            List<string> list = new List<string>() { "peter","lucky","banner"};
            Console.WriteLine(list[1]);
            //对象的形式
            Player player = new Player() { id=11,name="lucjy"};
            Console.WriteLine($"id={player.id},name={player.name}");
            //自定义对象
            var obj = new { id = 111, name = "lucky", data = 11 };
            Console.WriteLine($"id={obj.id},naem={obj.name},data={obj.name}");

            //?关于值类型,代表该值类型变量可以存储null值
            int? data = null;
            Console.WriteLine(data == null);//true
            Console.WriteLine(data != null);//false
            Console.WriteLine(data.HasValue);//false
            data = 11;
            Console.WriteLine(data.HasValue);//true

            //引用变量?代表的是判断不为null后调用相关方法
            Player player1 = null;
            //判断不为null在调用其方法
            player1?.ToString();
            string[] name = null;
            //判断不为null后再访问下标
            Console.WriteLine(name?[3]);
            Console.ReadKey();

추천

출처blog.csdn.net/weixin_51983027/article/details/129793572