Unity面向对象补全计划 之 List<T>与class(非基础)

C# & Unity 面向对象补全计划 泛型-CSDN博客

关于List,其本质就是C#封装好的一个数组,是一个很好用的轮子,所以并不需要什么特别说明

问题描述

假设我们有一个表示学生的类 Student,每个学生有姓名和年龄两个属性。我们需要创建一个学生列表,并实现以下功能:

  1. 添加学生到列表中
  2. 打印所有学生的信息(需要重写Tostring)
  3. 查找特定姓名的学生并打印其信息

解决思路

用一个List来保存每一个学生的信息

1.用List.Add方法添加学生

2.用foreachi遍历打印

3.用Find查找


数据图解

也就是说list<student> s

其中s[n]代表了一个个的student对象,而s[n].name,s[n].age才是我们要的数据,莫要搞混了

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Student : MonoBehaviour
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Student(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public override string ToString()
    {
        return $"Name: {Name}, Age: {Age}";
    }
}

管理类一览

cs 复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class StudentManager : MonoBehaviour
{
    List<Student> ss;
    private void Awake()
    {
        ss = new List<Student>();

        //添加
        ss.Add(new Student("张三",10));
        ss.Add(new Student("李四", 15));
        //遍历
        foreach (Student temp in ss)
        {
            Debug.Log(temp);
        }
        //查找
        string tempName1 = "张三";
        
        //注意下面这行我声明了一个临时的对象存储需要找到对象
        //Find可以传入函数所以我就使用了一个lambda表达式
        Student foundStudent1 = ss.Find((value)=>value.Name == tempName1);

        //其等价于
        //students.Find(delegate (Student s) {
        //    return s.Name == tempName1;
        //});

        if (foundStudent1 != null)        {

            Debug.Log($"已找到该学生{foundStudent1}");
        }
        else
        {
            Debug.Log($"未找到该学生{tempName1}");
        }
    }
}

注意事项:

添加和遍历并不难,查找需要特别说明一点,这里我用的Find甚至直接传入的lambda表达式

因为思路如下:

为什么不用Contains对比呢?

Contains 方法依赖于 Equals 方法和 GetHashCode 方法来判断列表中是否包含某个对象,如果非要用Contains 来写的话,就需要像下面这样重写这两个函数

cs 复制代码
    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        Student other = (Student)obj;
        return Name == other.Name && Age == other.Age;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Name, Age);
    }

使用的时候则需要创建一个临时变量,传入要查找的值,还需要实例化一下所以不是太方便了

cs 复制代码
Student tempName1= new Student("Bob", 22);
相关推荐
__water2 小时前
『功能项目』回调函数处理死亡【54】
c#·回调函数·unity引擎
__water2 小时前
『功能项目』眩晕图标显示【52】
c#·unity引擎·动画事件
__water3 小时前
『功能项目』第二职业法师的平A【57】
c#·unity引擎·魔法球伤害传递
__water5 小时前
『功能项目』战士的伤害型技能【45】
c#·unity引擎·战士职业伤害型技能
君莫愁。6 小时前
【Unity】检测鼠标点击位置是否有2D对象
unity·c#·游戏引擎
Lingbug7 小时前
.Net日志组件之NLog的使用和配置
后端·c#·.net·.netcore
咩咩觉主7 小时前
Unity实战案例全解析:PVZ 植物卡片状态分析
unity·c#·游戏引擎
Echo_Lee07 小时前
C#与Python脚本使用共享内存通信
开发语言·python·c#
__water14 小时前
『功能项目』QFrameWork框架重构OnGUI【63】
c#·unity引擎·重构背包框架
Crazy Struggle14 小时前
C# + WPF 音频播放器 界面优雅,体验良好
c#·wpf·音频播放器·本地播放器