Unity学习-C#

C#语言基础

.NET简介

  • dotnet
    • Microsoft新一代多语言的开发平台,用于构建和运行应用程序
  • C# csharp
    • 专为.net推出的高级编程语言
  • Mono
    • Novell公司支持在其他操作系统下开发.net程序的框架
    • Unity借助Mono实现跨平台,核心时.NET Framework框架

空白解决方案-添加控制台应用程序

using System;

//引入 命名空间

//定义命名空间【类的住址】:对类进行逻辑上的划分,避免重名
namespace Day01
{
    //定义类
    class Program
    {
        //定义方法
        //Main()方法-程序的入口
        static void Main(string[] args)
        {
            //程序从本行开始执行
            //修改程序面板 标题
            System.Console.Title = "第一个程序"; // 如果System 命名空间没有被引入,则需要在Console前面加上其命名空间
            //输出语句
            Console.WriteLine("Hello World!");
            Console.WriteLine("your name:");
            //输入语句
            string name = Console.ReadLine();

            Console.WriteLine("hello " + name);
            Console.ReadLine(); //让程序在本行暂停--使程序在命令行运行时,不会执行完后就立即退出

            //Rider中Run后,可以直接在看运行结果
            //代码.cs文件 - Run后 - bin-debug目录生成exe文件,可在命令行执行

            //Console 是类【工具】
            //  WriteLine / ReadLine 方法/功能
            //  Title - 属性 名词的修饰
            //给Unity写的就是 类【工具】
        }
    }
}

变量

using System;

namespace Day01
{
    class Program
    {
        static void Main(string[] args)
        {
            //命名规则
            //不能以数字开头 - 数字、字母、下划线组成 - 不能使用保留关键字
            
            //内置数据类型
            sbyte a = 1;        // 有符号字节型 -128 - 127
            byte b = 2;         // 无符号字节型 0 - 255 1个字节
            short c = 3;        // 有符号短整型 -32768 - 32767
            ushort d = 4;       // 无符号短整型 0 - 65535 2个字节
            int e = 5;          // 有符号整型
            uint f = 6;         // 无符号整型 4个字节
            long g = 7;         // 有符号长整型
            ulong h = 8;        // 无符号长整型 8个字节

            float numf = 1.2f;          //7位单精度-后缀f
            double numd = 1.23;         //15-16位双精度
            decimal numdd = 1.2323m;    //128位超高精度-后缀m

            char ch = 'a';      //2字节,存储单个字符,单引号
            string str = "hello world"; //字符串,存储文本,双引号
            bool isTrue = true; //布尔类型 true/false
            
            // 占位 {n}
            Console.WriteLine(string.Format("Oh! {0}",str));
            //标准数字字符串格式化
            Console.WriteLine("金额:{0:c}",10);  //金额:¥10.00
            //p-百分数显示(数字指定精度);d-整数(数字指定位数);f-浮点数(数字指定精度)
            
            //转义-  \0:空字符 等等
            
            
        }
    }
}
  • 调试
    • 在可能出错的行加断点
    • 启动调试
    • 逐句执行

数据基本运算

using System;

namespace Day01
{
    class Program
    {
        static void Main(string[] args)
        {
            int a ,b;
            // 赋值运算符
            a = 10;
            b = 5;
            Console.WriteLine("a={0},b={1}",a,b);
            // 算数运算符
            Console.WriteLine("a+b={0} a-b={1} a*b={2} a/b={3} a%b={4}",a+b,a-b,a*b,a/b,a%b);
            // 比较运算符
            Console.WriteLine("a>b={0} a<b={1} a==b{2} a!=b{3} a>=b{4} a<=b{5}",a>b,a<b,a==b,a!=b,a>=b,a<=b);
            Console.WriteLine("\"ab\"==\"ab\"? {0}","ab"=="ab");
            // 逻辑运算符
            bool c = true;
            bool d = false;
            Console.WriteLine("c={0} d={1}",c,d);
            //短路与、短路或
            Console.WriteLine("c&&d={0} c||d={1} !c={2}",c&&d,c||d,!c);
            // 快捷赋值运算符
            a += 2; //12
            a -= 3; //9
            a *= 3; //27
            a /= 9; //3
            a %= 2; //1
            Console.WriteLine(a);
            // 一元运算符
            Console.WriteLine(b++); //输出5  输出之后b增加1为6
            Console.WriteLine(++b); //b增加1为7 输出7
            // 三元运算符
            string str = a > b ? "a大" : "b大";
            Console.WriteLine(str);

        }
    }
}

数据类型转换

using System;

namespace Day01
{
    class Program
    {
        static void Main(string[] args)
        {
            string strNum = "18";
            int num1 = int.Parse(strNum);
            float num2 = float.Parse(strNum);
            Console.WriteLine("num1={0} num2={1}",num1,num2);
            //任意类型转换为string
            string str2 = num1.ToString();
            Console.WriteLine(str2);
            //string中的字符
            char c = str2[0];
            Console.WriteLine(c);
            
            //隐式转换-自动转换
            //显式转换-强制转换 eg:(byte)12

        }
    }
}

选择语句

using System;

namespace Day01
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个数字:");
            string sNum = Console.ReadLine();
            int num = int.Parse(sNum);
            char cha;
            
            //if语句
            if (num > 90 && num <=100)
            {
                cha = 'A';
            }
            else if(num > 80)
            {
                cha = 'B';
            }else if (num > 60)
            {
                cha = 'C';
            }else if (num >= 0)
            {
                cha = 'D';
            }
            else
            {
                cha = 'E';
            }
            
            //switch语句
            switch (cha)
            {
                case 'A':
                    Console.WriteLine("优秀!");
                    break;
                case 'B':
                    Console.WriteLine("良好!");
                    break;
                case 'C':
                    Console.WriteLine("及格!");
                    break;
                case 'D':
                    Console.WriteLine("不及格!");
                    break;
                default:
                    Console.WriteLine("非法值!");
                    break;
            }
            
            
        }
    }
}

循环结构

using System;

namespace Day01{
    class Program{
        static void Main(string[] args) {
            //for循环
            int sum = 0;
            for (int i = 1; i <= 100; i++){
                sum += i;
            }
            Console.WriteLine(sum);
            
            //while循环
            int sumW = 0;
            int j = 1;
            while (j <= 100){
                sumW += j;
                j++;
            }
            Console.WriteLine(sumW);
            
            //do-while循环
            int sumD = 0;
            int d = 1;
            do{
                sumD += d;
                d++;
            } while (d <= 100);
            Console.WriteLine(sumD);

            //跳转语句
            int sumB = 0;
            int b = 1;
            while (true){
                if (b <= 100){
                    sumB += b;
                    b++;
                    // continue;
                }else{
                    Console.WriteLine(sumB);
                    break;
                }
            }
        }
    }
}

随机数

//创建一个随机数工具
Random random = new Random();
//产生一个[1,101)之间的随机数
Console.WriteLine(random.Next(1, 101));

方法

using System;

namespace Day01{
    class Program{
        static void Main(string[] args) {

            Console.WriteLine(Add(3, 4));

            string str = "hello world!";
            //插入字符串
            Console.WriteLine(str.Insert(0,"haha"));
            //查询指定字符位置
            Console.WriteLine(str.IndexOf('a'));
            //移除指定位置n个字符
            Console.WriteLine(str.Remove(0,2));
            //替换字符串
            Console.WriteLine(str.Replace("world","C#"));
            //是否以xx开头
            Console.WriteLine(str.StartsWith('h'));
            //是否包含xx
            Console.WriteLine(str.Contains("hello"));
            //所有操作都不改变原字符串
            Console.WriteLine(str);
            
            
            //输出日历
            PrintYearCalendar(2021);
            

        }
        //方法
        //【访问修饰符】【可选修饰符】 返回类型 方法名称(参数列表){ //方法体; return x;}
        
        //方法名称--首字母大写
        private static int Add(int a, int b) {
            return a + b;
        }

        //是否为闰年
        private static bool IsLeapYear(int year) {
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
                return true;
            } else{
                return false;
            }
        }
        //指定月份天数
        private static int MonthDays(int year, int month) {
            switch (month){
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    return 31;
                case 4:
                case 6:
                case 9: 
                case 11:
                    return 30;
                case 2:
                    if (IsLeapYear(year)){
                        return 29;
                    } else{
                        return 28;
                    }
                default:
                    return -1;
            }
        }
        //指定日期的星期数
        private static DayOfWeek DayOfWeek(int year, int month, int day) {
            DateTime dt = new DateTime(year, month, day);
            return dt.DayOfWeek;
        }
        //输出月份日历
        private static void PrintMonthCalendar(int year, int month) {
            Console.WriteLine("{0}-{1}",year,month);
            Console.WriteLine("日\t一\t二\t三\t四\t五\t六");
            switch (DayOfWeek(year,month,1)){
                case System.DayOfWeek.Friday:
                    Console.Write("\t\t\t\t\t");
                    break;
                case System.DayOfWeek.Monday:
                    Console.Write("\t");
                    break;
                case System.DayOfWeek.Saturday:
                    Console.Write("\t\t\t\t\t\t");
                    break;
                case System.DayOfWeek.Sunday :
                    Console.Write("");
                    break;
                case System.DayOfWeek.Thursday:
                    Console.Write("\t\t\t\t");
                    break;
                case System.DayOfWeek.Tuesday:
                    Console.Write("\t\t");
                    break;
                case System.DayOfWeek.Wednesday:
                    Console.Write("\t\t\t");
                    break;
            }

            for (int i = 1; i <= MonthDays(year, month); i++){
                Console.Write(i+"\t");
                if (DayOfWeek(year, month, i) == System.DayOfWeek.Saturday){
                    Console.WriteLine();
                }
            }
            Console.WriteLine();
        }
        //输出年日历
        private static void PrintYearCalendar(int year) {
            for (int i = 1; i <= 12; i++){
                PrintMonthCalendar(year,i);
            }
        }
    }
}

方法重载\参数传递

using System;

namespace Day01{
    class Program{
        static void Main(string[] args) {
            //方法重载
            Console.WriteLine(Add(1,2));
            Console.WriteLine(Add(1,2,3));
            
            int a = 1;
            int b = 2;
            //按值传递-会为传入值创建新的存储位置,方法内操作不会改变此变量的值
            Swap(a,b);
            Console.WriteLine("a={0},b={1}",a,b);
            //按引用传递-传入的就是变量本身(存储位置相同),方法内操作会直接改变此变量
            Swap2(ref a,ref b);
            Console.WriteLine("a={0},b={1}",a,b);
            //按输出传递-即可以将函数结果输出到参数中
            int x;
            To100(out x);
            Console.WriteLine("x={0}",x);
        }

        //方法重载
        private static int Add(int a, int b) {
            return a + b;
        }
        private static int Add(int a, int b, int c) {
            return a + b + c;
        }
        
        //按值传递参数
        private static void Swap(int a, int b) {
            a = a + b;
            b = a - b;
            a = a - b;
        }
        //按引用传递-传递存储位置
        private static void Swap2(ref int a, ref int b) {
            a = a + b;
            b = a - b;
            a = a - b;
        }
        //按输出传递
        private static void To100(out int x) {
            x = 100;
        }
        
        
    }
}

数组

using System;

namespace Day01{
    class Program{
        static void Main(string[] args) {
            //数组
            int[] arr;
            arr = new int[12];
            arr[0] = 1;
            arr[1] = 1;
            for (int i = 2; i < arr.Length; i++){
                arr[i] = arr[i - 1] + arr[i - 2];
            }
            
            //foreach-var(同js中的var-自动判断类型)
            foreach (var num in arr){
                Console.Write(num+" ");
            }

            string[] strArr = new string[2] {"aa", "bb"};
            char[] cArr = {'a', 'b'};
            
            Console.WriteLine();
            Console.WriteLine("-----------");
            
            //数组方法
            //返回查找到的值的索引--IndexOf || LastIndexOf
            Console.WriteLine(Array.IndexOf(arr, 144));
            
            //复制元素  Array.Copy() || 数组.CopyTo()
            int[] arr2 = new int[] { 1,2,2};
            Array.Copy(arr,arr2,3);
            foreach (var i in arr2){
                Console.Write(i+" ");
            }
            Console.WriteLine();
            
            //排序
            int[] arr3 = {5, 2, 7, 2, 8, 4, 9, 1};
            Array.Sort(arr3);
            foreach (var VARIABLE in arr3){
                Console.Write(VARIABLE + " ");
            }
            Console.WriteLine();
            
            //反转
            Array.Reverse(arr3);
            foreach (var VARIABLE in arr3){
                Console.Write(VARIABLE + " ");
            }
            Console.WriteLine();
            
            //清空元素(值)
            Array.Clear(arr3,0,arr3.Length);
            foreach (var VARIABLE in arr3){
                Console.Write(VARIABLE + " ");
            }
            Console.WriteLine();
            
            //二维数组
            int[,] arr22 = new int[2,2];
        }

    }
}

交错数组

using System;

namespace Day02 {
    class Program {
        static void Main(string[] args) {
            //交错数组,每个元素都为一维数组,分布通常想象为“不规则的表格”
            int[][] arr = new int[4][];
            
            //创建一维数组,赋值给交错数组
            arr[0] = new int[3];
            arr[1] = new int[5];
            arr[2] = new int[9];
            arr[3] = new int[1];
        }
    }
}

2048

using System;

namespace Day01{
    class Program{
        static void Main(string[] args) {

            int[,] map = new int[4, 4];
            bool flag = true;

            string direction;
            
            AddOne(map, ref flag);
            PrintMap(map);
            
            while (!GameOver(map) && flag == false){
                Console.WriteLine("请输入方向(w-上,s-下,a-左,d-右:");
                direction = Console.ReadLine();
                Console.WriteLine(flag);
                switch (direction){
                    case "w":
                        MoveUp(map, ref flag);
                        break;
                    case "s":
                        MoveDown(map, ref flag);
                        break;
                    case "a":
                        MoveLeft(map, ref flag);
                        break;
                    case "d":
                        MoveRight(map, ref flag);
                        break;
                    default:
                        Console.WriteLine("输入有误!");
                        continue;
                }

                if (flag){
                    AddOne(map, ref flag);   
                }
                PrintMap(map);


            }
            

        }
        private static bool GameOver(int[,] map) {
            for (int i = 0; i < map.GetLength(0); i++){
                for (int j = 0; j < map.GetLength(1) - 1; j++){
                    if (map[i,j] == 0 || map[i,j+1] == 0 || map[i, j] == map[i, j + 1]){
                        return false;
                    }
                    if (map[j, i] == map[j + 1, i]){
                        return false;
                    }
                }
            }
            return true;
        }

        //TODO:需要原数组有改动才会增加
        private static void AddOne(int[,] map, ref bool flag) {
            Random random = new Random();
            int a, b, c;
            while (true){
                a = random.Next(0, 4);
                b = random.Next(0, 4);
                c = random.Next(0, 4);
                if (map[a, b] == 0){
                    map[a, b] = c > 0 ? 2 : 4;
                    flag = false;
                    return;
                }
            }

        }
        
        private static int[] ClearZero(int[] arr, ref bool flag) {
            int[] res = new int[arr.Length];
            int j = 0;
            for (int i = 0; i < arr.Length; i++){
                if (arr[i] != 0){
                    res[j] = arr[i];
                    j++;
                }
            }

            for (int i = 0; i < arr.Length; i++){
                if (res[i] != arr[i]){
                    flag = true;
                    break;
                }
            }
            return res;
        }

        private static int[] Merge(int[] arr,ref bool flag) {
            arr = ClearZero(arr, ref flag);
            for (int i = 0; i < arr.Length-1; i++){
                if (arr[i] != 0 && arr[i] == arr[i + 1]){
                    arr[i] += arr[i + 1];
                    arr[i + 1] = 0;
                    flag = true;
                }
            }
            arr = ClearZero(arr, ref flag);
            return arr;
        }

        private static int[,] MoveUp(int[,] map, ref bool flag) {
            int[] arr = new int[map.GetLength(0)];
            for (int i = 0; i < map.GetLength(1); i++){
                for (int j = 0; j < map.GetLength(0); j++){
                    arr[j] = map[j, i];
                }
                arr = Merge(arr, ref flag);
                for (int j = 0; j < map.GetLength(0); j++){
                    map[j, i] = arr[j];
                }
            }
            return map;
        }

        private static int[,] MoveDown(int[,] map, ref bool flag) {
            int[] arr = new int[map.GetLength(0)];
            for (int i = 0; i < map.GetLength(1); i++){
                for (int j = 0; j < map.GetLength(0); j++){
                    arr[j] = map[map.GetLength(0)-1-j, i];
                }
                arr = Merge(arr, ref flag);
                for (int j = 0; j < map.GetLength(1); j++){
                    map[map.GetLength(0)-1-j, i] = arr[j];
                }
            }
            return map;
        }

        private static int[,] MoveLeft(int[,] map, ref bool flag) {
            int[] arr = new int[map.GetLength(1)];
            for (int i = 0; i < map.GetLength(0); i++){
                for (int j = 0; j < map.GetLength(1); j++){
                    arr[j] = map[i, j];
                }
                arr = Merge(arr, ref flag);
                for (int j = 0; j < map.GetLength(0); j++){
                    map[i, j] = arr[j];
                }
            }
            return map;
        }
        private static int[,] MoveRight(int[,] map, ref bool flag) {
            int[] arr = new int[map.GetLength(1)];
            for (int i = 0; i < map.GetLength(0); i++){
                for (int j = 0; j < map.GetLength(1); j++){
                    arr[j] = map[i, map.GetLength(1)-1-j];
                }
                arr = Merge(arr, ref flag);
                for (int j = 0; j < map.GetLength(0); j++){
                    map[i, map.GetLength(1)-1-j] = arr[j];
                }
            }
            return map;
        }

        private static void PrintMap(int[,] map) {
            for (int i = 0; i < map.GetLength(0); i++){
                for (int j = 0; j < map.GetLength(1); j++){
                    Console.Write(map[i,j]+"\t");
                }
                Console.WriteLine();
            }
        }
        
    }
}

可变长参数

using System;

namespace Day02 {
    class Program {
        static void Main(string[] args) {
            
            Console.WriteLine(Add(1,2,3,4,5,6,7,8,9));
            
        }

        // 可变长参数
        private static int Add(params int[] arr) {
            int sum = 0;
            foreach (var item in arr){
                sum += item;
            }
            return sum;
        }
    }
}

数据类型

类型分类
  • 值类型:存储数据本身
    • 结构
      • 数值类型
      • bool
      • char
    • 枚举
  • 引用类型:存储数据的引用(内存地址)
    • 接口
      • string
      • Array
      • 委托
内存
  • 是CPU与其他外部存储器交换数据的桥梁
  • 用于存储遵照执行的程序与数据,即数据必须加载到内存才能被CPU处理
  • 通常开发人员表达的“内存”指内存条
分配
  • 程序运行时,CLR将申请的内存空间从逻辑上进行划分
  • 栈区:
    • 空间小(1MB),读取速度快
    • 用于存储正在执行的方法,分配的空间叫做栈帧,栈帧中存储方法的参数以及变量等数据。方法执行完毕后,对应的栈帧将被清除
  • 堆区:
    • 空间大,读取速度慢
    • 用于存储引用类型的数据
局部变量
  • 定义在方法内部的变量
  • 特点
    • 没有默认值,必须自行定义初始值,否则不能使用
    • 方法被调用时,存在栈中,方法调用结束时从栈中清除
值类型与引用类型
  • 值类型:声明在栈中,数据存储在栈中
  • 引用类型 :声明在栈中,数据存储在堆中,栈中存储该数据的引用
垃圾回收器
  • GC是CLR中一种针对托管堆自动回收释放内存的服务

  • GC线程从栈中的引用开始跟踪,从而判定哪些内存是正在使用的,若GC无法跟踪到某一块堆内存,那么就认为这块内存不再使用了,即为可回收的

成员变量
  • 定义在类中方法外的变量
  • 特点
    • 具有默认值
    • 所在类被实例化后,存在堆中,对象被回收后,成员变量从堆中删除
    • 可以与局部变量重名
拆装箱
  • 装箱
    • 值类型隐式转换为object类型或由此类型实现的任何接口类型的过程
    • 内部机制
      • 在堆中开辟内存空间
      • 将值类型的数据复制到堆中
      • 返回堆中新分配对象的地址
  • 拆箱
    • 从object类型到值类型或从接口类型到实现该接口的值类型 的显示转换
    • 内部机制
      • 判断给定类型是否是装箱时的类型
      • 返回已装箱实例中属于原值类型字段的地址
using System;

namespace Day02 {
    class Program {
        static void Main(string[] args) {

            int a = 1;
            //装箱操作
            Object o = a;   // 堆中开辟一块(int值,同步块索引,类型对象指针) - “比较”消耗性能
            //拆箱操作
            int b = (int) o;
            //形参object类型,实参传递值类型--装箱
            //可以通过 方法重载,泛型 避免

            string str = "" + 1;    //str = string.Concat("",1)   int-object
            string str2 = "" + 1.ToString();    //无装箱
        }

    }
}

可变字符串

using System;
using System.Text;

namespace Day02 {
    class Program {
        static void Main(string[] args) {
            
			// 可以在原有空间上修改
            StringBuilder strb = new StringBuilder();
            for (int i = 0; i < 100; i++){
                strb.Append(i);
            }
            Console.WriteLine(strb);
            
            //其他字符串方法
            //ToArray,Insert,Contains,ToLower,ToUpper,IndexOf,Substring,Trim,Split,Replace,Join
        }

    }
}

简单枚举

namespace Day01 {
    enum MoveDirection :int{
        Up = 0,
        Down = 1,
        Left = 2,
        Right = 3
    }
}

枚举多选

using System;

namespace Day02 {
    [Flags] //定义枚举时使用Flags修饰--表示此枚举可多选
    public enum PersonStyle {
        tall = 1,
        rich = 2,
        handsome = 4,
        white = 8,
        beauty = 16
    }
}

//-------------------------------------------------------------------------------

using System;
using System.Text;

namespace Day02 {
    class Program {
        static void Main(string[] args) {
            //在枚举中定义时,让每个枚举的数值为2^n,保证任意两个枚举值进行按位或运算时不会与枚举值重复
            PrintPersonStyle(PersonStyle.tall | PersonStyle.rich);
            
            //数据类型转换
            PrintPersonStyle((PersonStyle)2);
            Console.WriteLine((int)PersonStyle.beauty);
            //字符串-枚举
            PrintPersonStyle((PersonStyle)Enum.Parse(typeof(PersonStyle),"beauty"));
            //枚举-字符串
            Console.WriteLine(PersonStyle.handsome.ToString());
            
        }

        private static void PrintPersonStyle(PersonStyle style) {
            //使用 按位与运算,判断此多选枚举是否包含某一枚举值
            if ((style & PersonStyle.tall) == PersonStyle.tall){
                Console.WriteLine("高");
            }
            if ((style & PersonStyle.rich) == PersonStyle.rich){
                Console.WriteLine("富");
            }
            if ((style & PersonStyle.handsome) == PersonStyle.handsome){
                Console.WriteLine("帅");
            }
            if ((style & PersonStyle.white) == PersonStyle.white){
                Console.WriteLine("白");
            }
            if ((style & PersonStyle.beauty) == PersonStyle.beauty){
                Console.WriteLine("美");
            }
        }

    }
    
}

类与对象

namespace Day02 {
    public class Person {

        //数据成员-字段
        private string name;
        private int age;
        private string sex;
        
        
        //构造函数
        public Person() {
        }

        public Person(string name, int age):this() {
            this.Name = name;
            this.Age = age;
        }


        //方法成员
        
        //属性-保护字段,本质就是两个方法-当方法内部不需要其他语句时,可以简写
        public string Name { get;set;}
        public int Age {
            get { return this.age;}
            set { this.age = value; }
        }

        //属性:保护字段,本质就是两个方法
        public string Sex {
            get { return this.sex; }
            set { this.sex = value; }
        }
    }
}

//------------------------------------------------
using System;
using System.Text;

namespace Day02 {
    class Program {
        static void Main(string[] args) {

            Person p1 = new Person();
            p1.Name = "kk";
            p1.Age = 19;
            p1.Sex = "男";
            
            Console.WriteLine("姓名:{0},年龄{1},性别:{2}",p1.Name,p1.Age,p1.Sex);


        }

    }
    
}                                                                                                                                                                                                                                                                                                                       

集合与字典

using System;
using System.Collections.Generic;
using System.Text;

namespace Day02 {
    class Program {
        static void Main(string[] args) {

            //集合
            List<Person> list = new List<Person>(10);
            Person p1 = new Person();
            list.Add(p1);
            list.Add(new Person("k",19));
            list.Remove(p1);
            Person p2 = list[0];
            Console.WriteLine(p2.Age);
            
            
            //字典
            Dictionary<string, Person> dic = new Dictionary<string, Person>();
            dic.Add("k",new Person("k",19));
            Person p3 = dic["k"];
            Console.WriteLine(p3.Name);

        }

    }
    
}

继承

using System;
using System.Collections.Generic;
using System.Text;

namespace Day02 {
    class Program {
        static void Main(string[] args) {

            //继承
            Student s1 = new Student();
            s1.Name = "k";
            s1.sNumber = "202020202020";
            
            //类型转换
            Person p1 = new Person();
            //无法转换-会抛异常
            // Student s2 = (Student)p1;
            //使用as关键字进行转换,如果无法转换,不会抛异常,而是赋值为null
            Student s2 = p1 as Student;
        }

    }
    
}

static

静态成员变量
  • 使用static关键字修饰的成员变量
  • 静态成员变量属于类,类被加载时初始化,且只有一份。
  • 实例成员变量属于对象,在每个对象被创建时初始化,每个对象一份
  • 特点:存在优先与对象,被所有对象共享,常驻内存
静态构造函数
  • 初始化类的静态数据成员
  • 仅在类被加载时执行一次
  • 不允许使用访问修饰符
静态方法
  • 通过引用调用实例方法时,会隐式的传递对象引用,以便在方法内部可以正确访问该对象成员变量
  • 通过类名调用静态方法时,因为没有具体对象,所以在static方法中不能访问实例成员
静态类
  • 使用static关键字修饰的类
  • 不能实例化,只能包含静态成员
  • 静态类不能被继承,但是静态方法、属性都可以被继承
适用性:
  • 利:单独空间存储,所有对象共享,可直接被类名调用
  • 弊:静态方法中只能访问静态成员,共享数据被多个对象访问会出现并发
  • 适用场合:
    • 所有对象需要共享的数据
    • 在没有对象前就要访问成员
    • 工具类适合做静态类
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

namespace Day02 {
    class Program {
        static void Main(string[] args) {
            Test t1 = new Test();
            Test t2 = new Test();
            t1.Get(3);
            t2.Get(4);
            Test.PrintTotal();
            t1.PrintContain();
            t2.PrintContain();
        }

    }

    class Test {
        private static int total;
        private int contain;

        public Test() {
            //用于初始化非静态成员变量
            contain = 0;
        }

        static Test() {
            //用于初始化静态成员变量
            total = 100;
        }

        //从总数中获取num个,加入实例中
        public void Get(int num) {
            total -= num;
            contain += num;
        }

        //打印剩余总数
        public static void PrintTotal() {
            Console.WriteLine("Total:"+total);
        }

        //打印实例中持有的数量
        public void PrintContain() {
            Console.WriteLine("Contain:"+contain);
        }
        

    }
    
}

结构

  • 用于封装小型相关变量的值类型。与类语法相似,都可以包含数据成员和方法成员。但结构属于值类型,类属于引用类型
  • 适用性:表示点、颜色等轻量级对象。如创建存储1000个点的数组,如果使用类,将为每个对象分配更多内容,使用结构可以节约资源

Console.Clear() //清空

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CI_FAN

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

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

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

打赏作者

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

抵扣说明:

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

余额充值