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);
相关推荐
小码编匠6 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫13 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez201019 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫3 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎