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);
相关推荐
缺点内向2 小时前
C#编程实战:如何为Word文档添加背景色或背景图片
开发语言·c#·自动化·word·.net
学海无涯书山有路5 小时前
async-await异步编程
c#
切糕师学AI5 小时前
ARM 汇编器中的伪指令(Assembler Directives)
开发语言·arm开发·c#
lzhdim8 小时前
C#开发的提示显示例子 - 开源研究系列文章
开发语言·c#
人工智能AI技术8 小时前
【C#程序员入门AI】向量数据库入门:C#集成Chroma/Pinecone,实现AI知识库检索(RAG基础)
人工智能·c#
xb11328 小时前
C# 定时器和后台任务
开发语言·c#
A_nanda10 小时前
c# 用VUE+elmentPlus生成简单管理系统
javascript·vue.js·c#
wuguan_11 小时前
C#之线程
开发语言·c#
gc_229913 小时前
学习C#调用OpenXml操作word文档的基本用法(21:学习嵌入对象类)
c#·word·openxml·ole
老骥伏枥~13 小时前
C# if / else 的正确写法与反例
开发语言·c#