网站建设与管理课程总结,做网站做电脑版还是手机版好,郑州找人公司,网站排名有什么用C# Unity 面向对象补全计划 泛型-CSDN博客
关于List#xff0c;其本质就是C#封装好的一个数组#xff0c;是一个很好用的轮子#xff0c;所以并不需要什么特别说明 问题描述 假设我们有一个表示学生的类 Student#xff0c;每个学生有姓名和年龄两个属性。我们需要创…C# Unity 面向对象补全计划 泛型-CSDN博客
关于List其本质就是C#封装好的一个数组是一个很好用的轮子所以并不需要什么特别说明 问题描述 假设我们有一个表示学生的类 Student每个学生有姓名和年龄两个属性。我们需要创建一个学生列表并实现以下功能 添加学生到列表中打印所有学生的信息需要重写Tostring查找特定姓名的学生并打印其信息 解决思路 用一个List来保存每一个学生的信息 1.用List.Add方法添加学生 2.用foreachi遍历打印 3.用Find查找 数据图解 也就是说liststudent s 其中s[n]代表了一个个的student对象而s[n].names[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
{ListStudent ss;private void Awake(){ss new ListStudent();//添加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);