国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .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對象
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 司法| 海南省| 武川县| 青冈县| 新宁县| 南川市| 乐山市| 印江| 咸阳市| 六枝特区| 屏东县| 湘阴县| 于都县| 安陆市| 新余市| 桂平市| 平原县| 洞头县| 平顶山市| 额济纳旗| 彩票| 宝山区| 临邑县| 吴堡县| 姜堰市| 德阳市| 乌鲁木齐县| 光山县| 武隆县| 无棣县| 溆浦县| 威海市| 浦江县| 界首市| 张掖市| 巴东县| 盐源县| 金坛市| 林芝县| 贵德县| 文成县|