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);
相关推荐
大飞pkz1 小时前
【Unity】MVP框架的使用例子
unity·c#·mvc·框架·mvp·ui框架
电商api接口开发4 小时前
ASP.NET MVC 入门与提高指南六
c#·asp.net·mvc
宝桥南山4 小时前
Azure Devops - 尝试一下在Pipeline中使用Self-hosted Windows agent
microsoft·微软·c#·.netcore·azure·devops
冰茶_12 小时前
WPF之TextBox控件详解
学习·microsoft·微软·c#·wpf
大飞pkz16 小时前
【Unity】使用XML进行数据读存的简单例子
xml·unity·c#·游戏引擎·游戏开发·数据读写
编程乐趣21 小时前
基于C#开发的适合Windows开源文件管理器
开发语言·windows·c#
code_shenbing1 天前
C# 实现列式存储数据
开发语言·c#·存储
code_shenbing1 天前
.NET Core 数据库ORM框架用法简述
数据库·c#·.netcore·orm
ghost1431 天前
C#学习第20天:垃圾回收
开发语言·学习·c#
code_shenbing1 天前
WPF实现类似Microsoft Visual Studio2022界面效果及动态生成界面技术
ui·c#·wpf·上位机