【unity之c#专题篇】——进阶知识实践练习

news2024/9/22 15:35:01

在这里插入图片描述


👨‍💻个人主页:@元宇宙-秩沅

👨‍💻 hallo 欢迎 点赞👍 收藏⭐ 留言📝 加关注✅!

👨‍💻 本文由 秩沅 原创

👨‍💻 收录于专栏unityc#专题篇习题

在这里插入图片描述


习题总结专题篇

🅰️系统路线点击跳转


⭐【Unityc#专题篇】之c#核心篇】

⭐【Unityc#专题篇】之c#基础篇】

⭐【Unity-c#专题篇】之c#入门篇)

⭐【Unityc#专题篇】—基础章题单实践练习

【Unityc#专题篇】—核心章题单实践练习


文章目录

    • 习题总结专题篇
    • 🅰️系统路线点击跳转
    • 🎶前言
    • 🎶(==A==) 数组基类——Array类
    • 🎶(==B==) 数据集合——ArrayList类
    • 🎶(==C==)数据集合——Stack类
    • 🎶(==D==)数据集合——Queue类
    • 🎶(==E==)数据集合——Hashtable类散列表
    • 🎶(==F==)泛型
    • 🎶(==G==)泛型约束
    • 🎶(==H==)常用泛型数据结构类——List类
    • 🎶(==J==)常用泛型数据结构类——Dictionary类
    • 🎶(==L==)数据结构存储方式——顺序存储和链式存储
    • 🎶(==M==)常用泛型数据结构类——LinkedList类
    • 🎶(==N==)常见的数据容器的应用范围
    • 🎶(==O==)委托和事件——委托
    • 🎶(==P==)委托和事件——事件
    • 🎶(==Q==)委托和事件——匿名函数
    • 🎶(==R==)委托和事件——Lambda表达式
    • 🎶(==S==)委托和事件——List排序的三个方法
    • ⭐相关文章⭐


🎶前言

核心章知识点详解入口


🅰️ 题单来自:B站唐老狮


🎶(A 数组基类——Array类


  • 实践经验

    1.掌握三个常见的方法: 排序Sort,反转Reverser,复制Copy,清除Clear
   int[] a = { 1,4,2,5,3,8,6,7};
            //排序
            Array.Sort(a);
            foreach (int item in a)
            {
                Console.Write(" " + item);
            }
            Console.WriteLine();
            //反转
            string[] B = { "aa", "ss", "c" };
            Array.Reverse(a);
            Array.Reverse(B);
            foreach (int item in a)
            {
                Console.Write(" " + item);
            }
            Console.WriteLine();
            //复制
            int[] b=new int[8];
            Array.Copy(a,b,8);  //把a数组复制b中
            foreach (int item in b)
            {
                Console.Write(" " + item);
            }
            Console.WriteLine();

            //清除
            Array.Clear(a,0,a.Length );
            foreach (int item in a)
            {
                Console.Write(" " + item);
            }
            Console.WriteLine();

🎶(B 数据集合——ArrayList类


  • 实践经验

    1.ArrayList和Array的 区别:
    ①ArrayList是集合,Array是数组
    ②ArrayList长度不固定自动扩容,Array长度固定
    ③ArrayList可存储不同类型object,Array类型单一固定
    ④ArraList封装了增删等便捷方法,Array得手动操作
    ⑤ArrayList的长度是count,Array是Length
    2.当需要存储多个类型的数据,需要动态变化长度的时候用ArrayLIst
    3.增加Add,删除Remove,查找Indexof,长度Count,容量capacity

    4.应用于背包,仓库等容器物品的存取系统
    在这里插入图片描述

    /// <summary>
    /// 背包管理类
    /// </summary>
    class Knapsack
    {
        ArrayList knapsack = new ArrayList(10); //初始化容量
        private int money = 2000;
        /// <summary>
        /// 存储物品功能
        /// </summary>
        /// <param name="goods"></param>
        public void Save(Object goods )
        {
            knapsack.Add(goods);
            money += 50;
        }
        /// <summary>
        /// 卖出物品的功能
        /// </summary>
        /// <param name="goods"></param>
        public void Sell(Object goods)
        {
            knapsack.Remove(goods);
            money -= 50;
        }
        public void Show()
        {
            for (int i = 0; i<knapsack.Count  ; i++)
            {
                if (knapsack[i] is Food)
                {
                    Food fruit = knapsack[i] as Food;
                    Console.WriteLine(fruit.Name);
                    Console.WriteLine(money);
                }
            }
        }
    }
    class Food
    {
        public string Name { get; set; } = "苹果";
        public void Show() { Console.WriteLine("我是子类里面的方法"); }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Food apple   = new Food();
            Knapsack bag = new Knapsack();
            bag.Save(apple);
            bag.Show();  
        }
    }

🎶(C数据集合——Stack类


  • 实践经验

    1.十进制转二进制的原理: 除2取余
    2.Stack类里面没有单个删除和修改的方法
    3.应用于需要先进后出的情况

在这里插入图片描述

     class Program
    {
       public  Stack stack = new Stack();
        //栈的存取规则:先进后出
        /// <summary>
        /// 二进制方法转换
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public  void Form( int num) //原理除2取余
        {    
            while(num > 1)
            {
                stack.Push (num%2);       
                num /=2;             
            }
            stack.Push(num % 2);
        }
        static void Main(string[] args)
        {          
            try
            {
                Program text = new Program();
                Console.WriteLine("请输入任意一个整形数");
                int num = int.Parse(Console.ReadLine());
                text.Form(num);
                Console.WriteLine("栈现在的长度为:" + text.stack.Count );
                while(text .stack.Count !=0)
                { Console.Write(text.stack.Pop()); }
            }
            catch 
            {
                Console.WriteLine("请输入整形数字!");
            }
        }
    }

🎶(D数据集合——Queue类


  • 实践经验

    1.采用了线程的停顿方法1000帧1秒
    2.其他和Stack类一样

    在这里插入图片描述
 class Program
    {
        //Queue的存取规则是先进先出
        static void Main(string[] args)
        {
            int num = 10;
            Queue queue = new Queue();
            do
            {
                queue.Enqueue(num);
            } while (num-- != 0);
            Console.WriteLine("数据存取成功!打印如下:");
            try
            {
                while (queue != null)
                {
                    Console.WriteLine(queue.Dequeue());
                    Thread.Sleep(1000);
                }
            }
            catch 
            {
             Console.WriteLine("队列已空");
            }               
        }
    }

🎶(E数据集合——Hashtable类散列表


  • 实践经验

    1.最大作用就是采用键值对的形式提高查询的效率
    2.应用于某个名字和数据对象的存储应用

在这里插入图片描述

 /// <summary>
    /// 怪物对象
    /// </summary>
    class Monster
    {
        public string name;
        public int attack;
        public Monster(string name ,  int attack)
        {
            this.name = name;
            this.attack = attack;
        }
    }
    /// <summary>
    /// 怪物管理器对象
    /// </summary>
    class MonsterControl
    {
        public  Hashtable hashtable = new Hashtable();
        /// <summary>
        /// 创建怪物
        /// </summary>
        /// <param name="name"></param>
        /// <param name="attack"></param>
        public void CreatMonster(Monster boss)
        {

            hashtable.Add(boss.name, boss.attack);           
        }
        /// <summary>
        /// 移除怪物
        /// </summary>
        /// <param name="name"></param>
        public void RemoveMonster(string name)
        {
            hashtable.Remove(name);
        }
        /// <summary>
        /// 遍历怪物管理器
        /// </summary>
        public void Traverse()
        {
            foreach (DictionaryEntry  item in hashtable )
            {
                Console.WriteLine("怪物名称为{0},攻击力为{1}", item.Key, item.Value);
            }
        }
        static void Main(string[] args)
        {
            //hashtable 采用键值存取         
            Monster boss1 = new Monster("Rovanna", 999);
            Monster boss2 = new Monster("皮蛋", 666);
            Monster boss3 = new Monster("张三", 555);
            MonsterControl control = new MonsterControl();
            control.CreatMonster(boss1);
            control.CreatMonster(boss2);
            control.CreatMonster(boss3);
            control.Traverse();
        }
    }

🎶(F泛型


  • 实践经验

    1.基础万物之父的类型返回方法typeof()
    2.返回类型占用的字节方法sizeof()
    3.在泛型类中的泛型方法占位符是不一样的,最好手动区分
    在这里插入图片描述

    class Program
    {
        /// <summary>
        /// 判断返回的类型及其对应的字节
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type"></param>
        /// <returns></returns>
        public string  BankBit<K>()
        {
            // is判断的是地址id || == 判断的是值
            if (typeof(K) == typeof(int))         return "整形"+sizeof(int)+ "字节";
            else if (typeof(K) == typeof(char))   return "字符型" + sizeof(char ) + "字节";
            else if (typeof(K) == typeof(float ))  return "单精浮点型" + sizeof(float ) + "字节";
            else if (typeof(K) == typeof(string )) return "字符型" ;
            else return "其他类型";
        }
        static void Main(string[] args)
        {
            int a =1;
            Program type = new Program();
            Console.WriteLine (type.BankBit<int>());
            Console.WriteLine(type.BankBit<char>());
            Console.WriteLine(type.BankBit<float >());
            Console.WriteLine(type.BankBit<string>());
        }
    }

🎶(G泛型约束


  • 实践经验

    1.泛型约束实现单例模式基类被继承
    2.单例模式适用于一个项目中国只有一个实例对象
    3.可被忽略的缺点是在继承虽然可以限制成只有一个对象,但是还是可以new
    在这里插入图片描述
    /// <summary>
    /// 用泛型实现一个单例模式基类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    class SingleBase<T> where T:new()
    {
        //private SingleBase(){ } //这个可以不用写,要被继承
        static  private T instance = new T();
        static  public T Instance
        {
            get
            {
                return instance ;
            }
        }
    }
    class Text : SingleBase<Text>
    {
        //继承单例基类时,构造函数一定要有公共无参的
        public string Name { get; set; } = "俺是测试类";
    }
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine ( Text.Instance.Name  );
      

🎶(H常用泛型数据结构类——List类


  • 实践经验

    1.构造函数中调用自身对象用this
    2.LIst的函数和ArrryList的函数基本一致
    3.List和ArraryList最大的区别就是前者的本质是泛型数组,后者的本质是Object数组
    4.继承的时候,子类默认先调用父类的构造函数

在这里插入图片描述

  /// <summary>
    /// 13.List的删除和存取
    /// </summary>
    //class Program
   // {
        //List和ArrayList的区别:前者结合了泛型,避免了拆箱装箱,效率更加优化
        //static void Main(string[] args)
        //{ 
        //    List<int> text = new List<int>();
        //    int[] arrary = new int[10]{ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
        //    int i = 0;
        //    while (i<arrary.Length)
        //    {
        //        text.Add(arrary[i++]);
        //    }
        //    text.RemoveAt(5);
        //    foreach (int item in text)
        //    {
        //        Console.WriteLine(item);
        //    }
        //}
    //}
         
    ///在构造函数中用List存取元素
    class Monster
    {
       static public  List<Monster> control = new List<Monster>();
       public Monster()
        {
            control.Add(this); 
        }
        virtual public void attack() { }
    }
    class Boss : Monster
    {
        public override void attack()
        {
            Console.WriteLine("放大招");
        }
    }
    class Gablin : Monster
    {
        public override void attack()
        {
            Console.WriteLine("哥布林的技能");
        }
    }
    class Program
    {
    static void Main(string[] args)
    {
            Boss boss1 = new Boss();
            Gablin boss2 = new Gablin();
            Monster text = new Monster();
            foreach (Monster  item in Monster .control )
            {
                item.attack();
            }
    }
 }

🎶(J常用泛型数据结构类——Dictionary类


  • 实践经验

    1.不能再foreach迭代器里面修改键值不然会报错
    2.只要存在从一个数据获得另一个数据就可以应用Dictionary
    在这里插入图片描述
private  Dictionary<int, string> text = new Dictionary<int, string>();
        public Program()
        {
            string[] upperArrary = { "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾" };
            for (int i = 0; i < upperArrary.Length; i++)
            {
              text.Add(i + 1, upperArrary[i]);
            }
        }
        public void  Upper( string num  )
        {
            for (int i = 0; i < num.Length; i++)
            {
                int index = num[i] - '0';
                Console.Write(text[index]);
            }           
        }
        static void Main(string[] args)
        {
            Program Exam = new Program();
            Console.WriteLine(Exam.text[3]);
            try
            {           
                Console.WriteLine("请输入一个不超过三位数的整数");
                int num = int.Parse(Console.ReadLine());
                Exam.Upper(num.ToString());   
            }
            catch (Exception)
            {
                throw;
            }
        }

在这里插入图片描述

Dictionary<char, int> text = new Dictionary<char, int>();
      
        public void Multiplay(string arrray )
        {
            for (int i = 0; i < arrray.Length; i++)
            {
                if(text.ContainsKey(arrray[i]))
                {
                    text[arrray[i]] += 1;
                }
                else
                {
                    text.Add(arrray[i],1);
                }
            }
        }
       public  void Print()
        {
            foreach (KeyValuePair<char ,int> item in text)
            {
                Console.WriteLine(item);
            }
        }
        static void Main(string[] args)
        {
            Program text = new Program();
            string arrary = "Welcome to Unity World";
            string Arrary = arrary.ToUpper();         
            text.Multiplay(Arrary);
            text.Print();
        }

在这里插入图片描述


🎶(L数据结构存储方式——顺序存储和链式存储


  • 实践经验

    1.最大的应用区别在于顺序存储适合查改,链式存储适合增删
    2.构建链表时要考虑全面,考虑到每个节点相互之间的关系,看代码的逻辑性是否严谨
    在这里插入图片描述
 //1.
    //顺序存储是一组连续的存储单元依次存储在线性表中的存储 方式(连续存储)
    //链式存储是将一组任意不连续的存储单元存储在线性表中存储方式(任意存储)
    //2.
    //顺序存储的查改效率大于链式存储
    //链式存储的增删效率大于顺序存储
    //3.
    //常用的数据结构有:数组,链表,栈,队列,数,图,堆,散列表
 
    class LinkedNode<T>
    {   
        public T vaule;
        public LinkedNode(T Vaule)
        {
            this.vaule = Vaule;
        }
        public LinkedNode<T> peakLink = null;
        public LinkedNode<T> nextLink = null;
    }
    class Link<T>
    {
        private int count = 0;
        private LinkedNode<T> head;
        private LinkedNode<T> last;

        public int Count { get => count;  }
        public LinkedNode<T> Peak { get => head; }
        public LinkedNode<T> Last { get => last; }

        public void Add(LinkedNode<T> node) //添加节点
        {
            if (head == null)
            {
                head = node;
                last = node;
                count++;
            }
            else
            {
                //尾插法        
                LinkedNode<T> temp = last; ;
                last.nextLink = node;          
                last = node;
                last.peakLink = temp;
                count++;
            }
        }

        public void RemoveAt(int index) //删除节点
        {
            LinkedNode<T> Lnode = head ;
          
            int temp = 1;
            if (index > count || index < 1)
            {
                Console.WriteLine("超出链表规定范围,请输入正确范围进行移除操作!");
                return;
            }
            else if (index == 1)
            {
                Console.WriteLine("指令为删除头节点");
                head = head.nextLink;
            }
            else if (index == count)
            {
                Console.WriteLine("指令为删除尾节点");
                
                last = last.peakLink;
                Console.WriteLine("此时尾节点为:" + last.vaule);
                last.nextLink = null;
              
            }
            else
            {
                while (true)
                {
                    if (temp == index)
                    {
                        if (Lnode.peakLink != null)
                            Lnode.peakLink.nextLink = Lnode.nextLink;
                        if (Lnode.nextLink != null)
                            Lnode.nextLink.peakLink = Lnode.peakLink;
                        break;
                    }
                    temp++;
                    count--;
                    Lnode = Lnode.nextLink;
                }
            }
        }

        public void Print() //遍历所有节点
        {
            LinkedNode<T> Lnode = head;
            
            while(Lnode != null )
            {
                Console.WriteLine("节点的值为:"+Lnode.vaule );
                Lnode = Lnode.nextLink;
            }

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Program text = new Program();
            LinkedNode<int> node1 = new LinkedNode<int>(1);
            LinkedNode<int> node2 = new LinkedNode<int>(2);
            LinkedNode<int> node3 = new LinkedNode<int>(3);
            Link<int> list = new Link<int>();
            list.Add(node1);
            list.Add(node2);
            list.Add(node3);
            Console.WriteLine("此时链表的长度为:" + list.Count);
            list.RemoveAt(2);
            list.Print();
        }       
    }

🎶(M常用泛型数据结构类——LinkedList类


  • 实践经验

    1.本质上就是泛型的双向链表
    2.当需要进行节点操作的时候,才用到节点类的API
    3.所以需要掌握LinkedList 和LinkedListNode两个类

    在这里插入图片描述

            LinkedList<int> list = new LinkedList<int>();
            Random rand = new Random();
            int temp = 10;
            while(temp-->=1)
            {
                list.AddFirst(rand.Next(101));
            }
            //foreach遍历
            //foreach (var item in list)
            //{
            //    Console.WriteLine(item);
            //}
            LinkedListNode<int> node = list.First;
            //节点遍历——头节点遍历
            Console.WriteLine("从头部开始 遍历了");
            while(node!= null )
            {
                Console.WriteLine(node.Value);
                node = node.Next;
            }
            //节点遍历 ——尾节点遍历\
            Console.WriteLine("从尾部开始 遍历了");
            node = list.Last;
            while (node != null)
            {
                Console.WriteLine(node.Value);
                node = node.Previous ;
            }

🎶(N常见的数据容器的应用范围


总结数组,list,Dectionary,Stack,Queue,LinkedList等存储容器。我们怎么来使用

  • 数组:简单的数据类型存储的时候,或者只需要查改数据的时候
  • List:它是ArraryList的泛型升级,适合一切对象的存储
  • LinkeList:它是泛型双向链表,适合频繁增删的数据对象的情况下使用
  • Dectionary:它是Hashtable的泛型升级,适合键值对象的存储
  • Stack:适合先进后出的情况下使用
  • Queue:适合先进先出的情况下使用

🎶(O委托和事件——委托


  • 实践经验

    1.委托有两种调用得方式:xx() 和 xx.Invoke();
    2.if 和委托调用的简便写法:XX?.Invoke();
    3.委托可以理解为,把工作或者一系列工作安排给谁做。做工作是行为,那么也就是方法,所以是将方法或一系列方法进行传递
    4.c#中自定义的两种类型的委托(无返回值 Action ,有返回值Fun)
    在这里插入图片描述
 class Person
    {
        virtual public void Eat()
        {
            Console.WriteLine("吃饭");
        }
    }
    class Mother:Person
    {
        public Action Cook;
        public Mother()
        {
            Cook = cook;
            Cook += OpenEat;
            Cook += Eat;
        }
        public void cook()
        {
            Console.WriteLine("今天妈妈做饭");
        }
        public  void  OpenEat()
        {
            Console.WriteLine("开吃");
        }
        public override void Eat()
        {
            Console.WriteLine("我是妈妈我吃饭了");
        }
    }
    class Father:Person
    {
        public override void Eat()
        {
            Console.WriteLine("我是爸爸我吃饭了");
        }
    }
    class Children:Person
    {
        public override void Eat()
        {
            Console.WriteLine("我是儿子我吃饭了");
        }
    }
    class Program
    {
        
        static void Main(string[] args)
        {
            Mother mother = new Mother();
            Father father = new Father();
            Children children = new Children();
            mother.Cook += father.Eat;
            mother.Cook += children.Eat;
            mother.Cook();
            //委托增加后也伴随着减,多的话全部清空
            mother.Cook = null;

        }
    }
在这里插入代码片

在这里插入图片描述

  #region    怪物死亡的逻辑     
    
    class Monster
    {
        public  Action<Monster> BossDeadDo;
        public int selfMoney = 10;
        public void Dead()
        {
            Console.WriteLine("怪物已经死亡");
            BossDeadDo?.Invoke(this); 
            //死亡后直接调用委托
            //委托调用的第二种方式——简化代码
            BossDeadDo = null;
            //委托增加过后也得删除,或者清空
        }
    }
    class Player
    {
        public int money = 0 ;
        public void AddMoney(Monster boss) //增加怪物掉下来的金币
        {
            money += boss.selfMoney;
            Console.WriteLine("您得财产为{0}",money );
        }

    }
    class GUI
    {
        public int money = 0;
        
        public void UpdateGui(Monster boss) //更新获得得金币分数
        {
            money += boss.selfMoney;
            Console.WriteLine("您已获得{0}个金币", money);
        }

    }
    class Result
    {
        public int num = 0;
        public void Addnum(Monster boss)
        {
            num++;
            Console.WriteLine("您已击败{0}个怪物",num);
        }
    }
    class Progranm
    {

        static void Main(string[] args)
        {
            GUI gui = new GUI();
            Player  player = new Player();
            Result  result = new Result();
            Monster monster = new Monster();
            monster.BossDeadDo += player.AddMoney;
            monster.BossDeadDo += result.Addnum;
            monster.BossDeadDo += gui.UpdateGui;
            monster.Dead();
            monster.Dead();
        }

🎶(P委托和事件——事件


  • 实践经验

    1.事件就是为了防止委托在外部被调用或赋值,防止被置空
    (只能作为类,接口,结构体中的成员变量)
    2.延时显示while(true)if(xx%99999)——关键是被除数多大,越大显示的越慢
    3.让委托更加安全

在这里插入图片描述

    class AddHotMachine //加热器
    {
        public event Action<int> WarmDoEvent;
        public int temperature = 0;
        public void charge()
        {
            Console.WriteLine("已通电");
            int Index = 0;
            while(true) //让加热有间隔时间
            {
                if (Index % 99999999== 0) //简单的时间间隔器
                {
                    temperature++;
                    Console.WriteLine("此时水温为" + temperature);
                    Index = 0;
                    if (temperature >= 100) break;
                    else if (temperature > 95)
                    {
                        WarmDoEvent(temperature);
                    }
                }
                ++Index;
            }
        }    
    }
    class WarmMachine  //报警器
    {
        public void Worm(int temp)
        {
            Console.WriteLine("报警!此时水温为:"+temp);
        }
    }
    class ShowMachine  //显示器
    {
        public void show(int temp)
        {
            Console.WriteLine("水已经烧开");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            WarmMachine warm = new WarmMachine();
            ShowMachine show = new ShowMachine();
            AddHotMachine addHot = new AddHotMachine();
            addHot.WarmDoEvent += warm.Worm;
            addHot.WarmDoEvent += show.show;
            addHot.charge();
        }
    }
}

🎶(Q委托和事件——匿名函数


  • 实践经验

    1.匿名函数的好处就是不用声明,直接写出方法体使用
    2.委托函数的返回函数的写法更改了函数局部变量的生命周期 —闭包

在这里插入图片描述

 class Program
    {
       //委托函数返回函数的写法 ——>
       static  public Func<int,int> print( int m)
        {
            return delegate (int v) { return m * v; };
        }
   
        static void Main(string[] args)
        {
        //委托函数返回函数的调用
            Func<int, int> text = print(4);
            Console .WriteLine(text(25));
          
        }
    }
}

🎶(R委托和事件——Lambda表达式


  • 实践经验

    1.改题目就是解决闭包时局部变量在父类函数范围内为最终值得情况
    2.解决方法就是声明一个中间变量Index

在这里插入图片描述

 class Program
    {
        //题目就是为了解决闭包的第二个特点,在父类函数中的局部变量是范围内的最终值
       static public Action  Print()
        {
            Action action = null;
            for (int i = 1; i <= 10; i++)
            {
                int index = i;
                action += () => {
                Console.WriteLine(index);
                };
            }
            return  action;           
        }
        static void Main(string[] args)
        {
            Action text = Print();
            text();
        }
    }

🎶(S委托和事件——List排序的三个方法


  • 实践经验

    1.排序的这几个方法,第三个(利用参数是委托的Sort方法重载)最为简便,当然第二个利用继承接口自定义规则函数也可以
    2.第二个题目,利用了枚举的成员和数字的对象方法,进行了规则判断
    3.应用于,多规则排序问题,和对于字典(键值对)数据的排序

在这里插入图片描述

 class Monster
    {
        public string name;
        public int attack;
        public int defence;
        public int blood;
        public Monster(string name, int a, int d, int b)
        {
            this.name = name;
            attack = a;
            defence = d;
            blood = b;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Monster> boss = new List<Monster>();
            boss.Add(new Monster("boss2", 33, 44, 66));
            boss.Add(new Monster("boss3", 44, 55, 77));
            boss.Add(new Monster("boss1", 66, 33, 55));
            Console.WriteLine("请输入以下数字来选择您饲养怪物的战力排名");
            try
            {
                int selection = int.Parse(Console.ReadLine());
                switch (selection)
                {
                    case 1://攻击排序
                        boss.Sort(
                            (Monster a, Monster b) =>
                            {
                                return a.attack < b.attack ? 1 : -1;
                            });
                        break;
                    case 2://防御排序
                        boss.Sort(
                           (Monster a, Monster b) =>
                           {
                               return a.defence < b.defence ? 1 : -1;
                           });
                        break;
                    case 3://血量排序
                        boss.Sort(
                       (Monster a, Monster b) =>
                       {
                           return a.blood < b.blood ? 1 : -1;
                       });
                        break;
                    case 4://反转
                        boss.Reverse();
                        break;
                    default:
                        break;
                }
            }
            catch
            {
                Console.WriteLine("您的输入无效请按规定输入");
            }
            foreach (Monster item in boss)
            {
                Console.WriteLine(item.name);
            }
        }
    }

在这里插入图片描述

  • 利用枚举的转换知识点,并且利用第二个放法(继承接口)来进行排序
    //*********************************
    //排序规则:
    //类型:国用 ,军用,民用
    //品质:红,绿,白
    //*********************************
    enum Quality
    {= 1,
        绿,}
    enum Type
    {
        国用 = 1,
        军用,
        民用
    }
    class Goods : IComparable<Goods>
    {
        
        public string type;
        public string name;
        public string quality;
        public Goods( string type,string name ,string quality)
        {
            this.name = name;
            this.quality = quality;
            this.type = type;
      
        }
        public int CompareTo(Goods other)
        {
           // 当类型不同先比类型
            if (other.type != this.type)
            {
                Type a ,b;
                Enum.TryParse(other.type, out a);
                Enum.TryParse(this.type, out b);
                return (int)a >(int)b ? -1 : 1;
            }
            else if (other.quality != this.quality)
            {
                Quality a, b;
                Enum.TryParse(other.quality , out a);
                Enum.TryParse(this .quality, out b);
                return (int)a > (int)b ? -1 : 1;
            }
            else if (other.name.Length < this.name.Length)
                return - 1;
                return 1;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Goods> goods = new List<Goods>();
            Goods knif1 = new Goods("民用","民用小刀1","绿");
            Goods knif2 = new Goods("民用", "民用小刀2", "红");
            Goods knif3 = new Goods("军用", "军用尼泊尔", "绿");
            Goods knif4 = new Goods("国用", "国剑", "白");
            Goods knif5 = new Goods("国用", "国剑", "红");
            Goods knif6 = new Goods("军用", "军用尼泊尔", "红");
            goods.Add(knif1);
            goods.Add(knif2);
            goods.Add(knif3);
            goods.Add(knif4);
            goods.Add(knif5);
            goods.Add(knif6);
            goods.Sort();
            foreach (Goods item in goods)
            {
                Console.WriteLine(item.name+" "+item.type +" "+item .quality );
            }
        }

在这里插入图片描述


    #region List对dictionary进行排序
    class Program
    {

        static void Main(string[] args)
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>();
            dictionary.Add("火娃", 1); 
            dictionary.Add("金娃", 4);
            dictionary.Add("木娃", 5);
            dictionary.Add("土娃", 3);
            dictionary.Add("水娃", 2);
            List<KeyValuePair<string, int>> ssssot = new List<KeyValuePair<string, int>>();
            foreach(KeyValuePair<string, int> item in dictionary )
            {
                ssssot.Add(item);
            }
            ssssot.Sort((a,b) => {
                if (a.Value < b.Value)
                    return -1;
                    return 1;
            });
            foreach (KeyValuePair<string, int> item in ssssot )
            {
                Console.WriteLine(item );
            }
        }

⭐相关文章⭐

⭐【Unityc#专题篇】之c#核心篇】

⭐【Unityc#专题篇】之c#基础篇】

⭐【Unity-c#专题篇】之c#入门篇)

⭐【Unityc#专题篇】—基础章题单实践练习

【Unityc#专题篇】—核心章题单实践练习



你们的点赞👍 收藏⭐ 留言📝 关注✅是我持续创作,输出优质内容的最大动力!

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

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

相关文章

如果你很焦虑、浮躁,不如去读一读林曦这本《无用之美》

生活中不可或缺的是柴米油盐&#xff0c;而濡养人心的往往是无用之美。——林曦    很难用语言写出这本书的美。有些书会给你带来内心的激荡&#xff0c;有些会让你充满力量&#xff0c;而林曦老师的书便自带一种轻盈的美&#xff0c;越往下读越能让人凝神静气。      …

浅谈一下@Async和SpringSecurityContext可能会遇到的问题和解决方案

Async和SpringSecurityContext 场景回溯 在执行一个用时较长的批量插入业务的时候,我尝试使用Async异步对业务进行优化,但是却给我报了空指针的错误,定位之后发现 此处我是基于SpringSecurity来获取用户的 是currentUserService获取到的当前登陆用户为空导致的,但是当前确实是…

文心一言 VS 讯飞星火 VS chatgpt (27)-- 算法导论5.1 2题

二、请描述 RANDOM(a&#xff0c;b)过程的一种实现&#xff0c;它只调用 RANDOM(0&#xff0c;1)。作为a和b的函数&#xff0c;你的过程的期望运行时间是多少? 文心一言&#xff1a; 假设我们有一个伪随机数生成器&#xff0c;可以生成在[0,1)范围内的随机数。那么我们可以使…

深入探讨JMeter中不为人知的JSONPath用法

在jmeter使用过程中&#xff0c;我们经常会看到接口返回数据类型为application/json&#xff0c;也就时我们常说的json格式。 而在功能测试时&#xff0c;我们经常会要对它的结果进行断言&#xff0c;确认结果是否与预期一致&#xff0c;有时候还会想从结果中提取某个值&#…

第十六章行为性模式—职责链模式

文章目录 职责链模式解决的问题结构实例存在的问题 JavaWeb 源码 - FilterChain 行为型模式用于描述程序在运行时复杂的流程控制&#xff0c;即描述多个类或对象之间怎样相互协作共同完成单个对象无法单独完成的任务&#xff0c;它涉及算法与对象间职责的分配。行为型模式分为类…

知识蒸馏:综述

本文主要是针对2021年 IJCV Knowledge Distillation: A Survey的一个翻译。 知识蒸馏&#xff1a;综述 摘要1 引言2 知识2.1 基于响应的知识2.2 基于特征的知识2.3 基于关系的知识 3 蒸馏方案3.1 离线蒸馏3.2 在线蒸馏3.3 自蒸馏 4 师生结构5 蒸馏算法5.1 对抗蒸馏5.2 多教师蒸…

SpringBoot @ConditionalOnProperty注解 + AOP切面控制日志打印

参考资料 ConditionalOnProperty的作用和用法 目录 一. 前期准备1.1 错误信息实体类1.2 自定义校验异常1.3 业务页面1.3.1 前台HTML1.3.2 Form实体类1.3.3 Controller层1.3.4 Service层 二. ConditionalOnProperty注解和AOP切面的使用2.1 配置文件2.2 AOP切面 ConditionalOnP…

深剖 Linux 信号量

目录 传统艺能&#x1f60e;POSIX信号量&#x1f60d;概念&#x1f602; 信号量函数&#x1f60d;初始化信号量&#x1f44c;销毁信号量&#x1f44c;等待&#xff08;申请&#xff09;信号量&#x1f44c;发布&#xff08;释放&#xff09;信号量&#x1f923; 二元信号量模拟…

Linux下C、C++、和Java程序设计

1.创建用户和之前一样。 RHEL7.2用户名和密码的创建以及DHCP服务的安装_封奚泽优的博客-CSDN博客https://blog.csdn.net/weixin_64066303/article/details/130763469?spm1001.2014.3001.55012.用yum安装&#xff08;分别是c,c,java,javac)(之前我以为是分开安装的&#xff0c…

Sui Builder House首尔站倒计时!

Sui主网上线后的第一场Builder House活动即将在韩国首尔举行&#xff0c;同期将举办首场线下面对面的黑客松。活动历时两天&#xff0c;将为与会者提供独特的学习、交流和娱乐的机会。活动详情请查看&#xff1a;Sui Builder House首尔站&#xff5c;主网上线后首次亮相。 Sui…

2. 虚拟环境

一、为什么要搭建虚拟环境&#xff1f; 在实际开发过程中&#xff0c;多个程序可能需要调试各种版本的不同环境&#xff0c;比如不同的Python解释器&#xff0c;不同的flask版本 二、如何搭建虚拟环境&#xff1f; 什么是虚拟环境&#xff1f; 它就是一个特殊的文件夹&…

一个matlab colorbar的简易代码cmocean

matlab自带的色阶不全&#xff0c;无法满足绘图的需求&#xff0c;而cmocean函数提供了一些常用的色阶。 函数命令&#xff1a;cmocean(ColormapName,varargin)&#xff0c;其中的ColormapName有如下的可选参数&#xff1a; 各个参数的绘图效果如下&#xff1a; 另外的一个参…

基于CAPL版本的CRC32算法

&#x1f345; 我是蚂蚁小兵&#xff0c;专注于车载诊断领域&#xff0c;尤其擅长于对CANoe工具的使用&#x1f345; 寻找组织 &#xff0c;答疑解惑&#xff0c;摸鱼聊天&#xff0c;博客源码&#xff0c;点击加入&#x1f449;【相亲相爱一家人】&#x1f345; 玩转CANoe&…

UI设计用什么软件做?

1、即时设计 即时设计是一款国内的在线协同设计工具&#xff0c;提供原型设计、UI/UX 设计和设计交付等核心功能。它无需第三方插件&#xff0c;拥有丰富的组件样式、中英文字体库和本地化资源&#xff0c;受到专业设计师的好评。与其他国外的 UI 工具相比&#xff0c;即时设计…

加拿大访问学者博士后签证材料清单指南

加拿大作为一个受欢迎的留学和研究目的地&#xff0c;吸引着许多国际学者和博士后前往交流和深造。作为准备申请加拿大访问学者或博士后签证的申请人&#xff0c;准备充分的材料是至关重要的。下面是知识人网小编整理的个关于加拿大访问学者博士后签证材料清单的指南&#xff0…

mysql-xtrabackup的使用

一、安装 1.下载压缩包 根据当前地址选择对应的版本和系统 wget https://downloads.percona.com/downloads/Percona-XtraBackup-2.4/Percona-XtraBackup-2.4.28/binary/tarball/percona-xtrabackup-2.4.28-Linux-x86_64.glibc2.17.tar.gz2.解压缩 tar xvf percona-xtrabac…

【分布鲁棒和多目标非负矩阵分解】基于DR-NMF的对NMF问题噪声模型的识别鲁棒性研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

A*寻路之旅:用SDL图形化演示

前言 欢迎来到小K的数据结构专栏的第十小节&#xff0c;本节将为大家带来A*寻路算法的图形化详解&#xff0c;学了之后寻路不再迷路&#xff08;✨当然也为大家准备了完整的源码&#xff0c;好像在文章顶部欸~ &#xff09;~希望你看完之后&#xff0c;能对你有所帮助&#xff…

ctfshow 每周大挑战 RCE极限挑战4、5

看过官方wp之后复现的&#xff0c;用的payload是自己后来写的&#xff0c;可能不如官方的看着清晰 有点强迫症似的在抠细节&#xff08;x 目录 挑战4最初的思路通过HackBar拿flag的写法写法一写法二 挑战5burp中的payload 大佬们也太极限啦 挑战4 最初的思路 第4题的长度限制…

UM2082F08 125k三通道低频无线唤醒ASK接收功能的SOC芯片 汽车PKE钥匙

1产品描述 UM2082F08是基于单周期8051内核的超低功耗8位、具有三通道低频无线唤醒ASK接收功能的SOC芯片。芯片可检测30KHz~300KHz范围的LF (低频)载波频率数据并触发唤醒信号&#xff0c;同时可以调节接收灵敏度&#xff0c;确保在各种应用环境下实现可靠唤醒&#xff0c;其拥…