首页 > 编程 > .NET > 正文

集合类List与Dictonary实例练习

2024-07-10 12:46:22
字体:
来源:转载
供稿:网友
a、List<>泛型集合
代码如下:
View Code
using System;
using System.Collections.Generic;
namespace _02_泛型集合 {
class Person {
public Person(string name, int age) {
this .name = name;
this .age = age;
}
private string name;
public string Name {
get {
return name;
}
set {
name = value ;
}
}
private int age;
public int Age {
get {
return age;
}
set {
age = value ;
}
}
}
class Student : Person {
public Student(string name, int age)
: base (name, age) {
}
}
class Teacher : Person {
public Teacher(string name, int age)
: base (name, age) {
}
}
class Program {
static void Main( string[] args) {
Student xyy = new Student( "小月月" , 12);
Student fj = new Student( "凤姐" , 14);
Student fr = new Student( "芙蓉姐姐" , 16);
Student xl = new Student( "犀利哥" , 18);
List <Student > student = new List <Student >();
student.Add(xyy);
student.Add(fj);
student.Add(fr);
student.Add(xl);
Teacher tea = new Teacher( "wanghao" , 21);
//student.Add(tea);//因为List<Student> 限制类型必须为Student 所以不能添加Teacher对象
//比ArrayList更加限制存储的类型 而且效率要高 因为添加 取出对象是不会发生装箱 拆箱的操作的
//遍历
foreach (Student item in student) {
Console .WriteLine(item.Name);//因为返回的就是student对象 所以可以直接读取属性值
Console .WriteLine(item.Age);
}
//移除
student.Remove(xyy); //移除的是引用地址 所以下面移除的s不是xyy
Student s = new Student( "小月月" , 12);
student.Remove(s);
student.RemoveAt(0);
student.RemoveRange(0, 2); //从0索引移除后面两位 即前移除前两位学生 xyy fj
//student.RemoveAll();//移除所有满足条件的 详见帮助文档
student.Clear();
Console .WriteLine(student.Contains(xyy));
//ToArray()方法 转换学生类型数组
Student [] stu = student.ToArray();
foreach (Student item in stu) {
Console .WriteLine(item.Name);
}
Console .Read();
}
}
}

b、Dictonary<>字典
代码如下:
View Code
using System;
using System.Collections.Generic;
namespace _03_泛型集合 {
class Student {
public Student(string name, int age) {
this .name = name;
this .age = age;
}
private string name;
public string Name {
get {
return name;
}
set {
name = value ;
}
}
private int age;
public int Age {
get {
return age;
}
set {
age = value ;
}
}
}
class Program {
static void Main( string[] args) {
Student xyy = new Student( "小月月" , 12);
Student fj = new Student( "凤姐" , 14);
Student fr = new Student( "芙蓉姐姐" , 16);
Student xl = new Student( "犀利哥" , 18);
Dictionary <string , Student> student = new Dictionary < string, Student >();//key为string类型的name value为Student对象
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表