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才是我们要的数据,莫要搞混了

 

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}";
    }
}

管理类一览 

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 来写的话,就需要像下面这样重写这两个函数

    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);
    }

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

Student tempName1= new Student("Bob", 22);
  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值