您的位置:首页 > 编程语言 > C#

c#学习笔记之泛型

2010-05-26 12:42 351 查看
举报

c#学习笔记之泛型

热9时浩勇 2010-05-13 16:49

三星Bada开发者聚会报名中
泛型是通过“参数化类型”来实现在同一则代码中操作多种数据类型。

首先声明这种泛型数据类型,声明时不用指定要处理的数据的类型,只讨论抽象的数据操作,如排序、查找等。

泛型接口

泛型接口通常用来为泛型集合类或者表示集合元素的泛型类定义接口。对于泛型类来说,从泛型接口派生可以避免值类型的装箱和拆箱操作。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication15

{

public class person

{

public string name;

public char sex;

public string department;

public person(string name1, char sex1, string department1)

{

name = name1;

sex = sex1;

department = department1;

}

}

public class student : person

{

public student(string name1, char sex1, string department1)

: base(name1, sex1, department1)

{

}

public string getinfo()

{

string result = "姓名:" + name;

result += "/t性别" + sex;

result += "/t班级" + department;

return result;

}

}

public class teacher : person

{

public teacher(string name, char sex, string department)

: base(name, sex, department)

{

}

}

public class persons<T> where T : person

{

private T[] person_1 = new T[5];

//索引器

public T this[int index]

{

get

{

if (index < 0 || index >= 5) return person_1[0];

else return person_1[index];

}

set

{

if (index < 0 || index >= 5) person_1[0] = value;

else person_1[index] = value;

}

}

public int count

{

get

{

int i;

for (i = 0; i < person_1.Length; i++)

{

if (this[i] == null) break;

}

return i;

}

}

public string getinfo(int index)

{

string result = "姓名:" + this[index].name;

result += "/t性别:" + this[index].sex;

result += "/t部门:" + this[index].department;

return result;

}

}

class Program

{

static void Main(string[] args)

{

persons<student> s = new persons<student>();

s[0]=new student("张伟",'男',"计本0801");

s[1]=new student("王晓斌",'男',"计算机");

s[2]=new student("范围",'女',"会计");

Console.WriteLine("以下是学生名单:");

for (int i = 0; i < s.count; i++)

{

string result = s[i].getinfo();

Console.WriteLine(result);

}

persons<teacher> t = new persons<teacher>();

t[0] = new teacher("王斌", '男', "计算机教研");

t[1] = new teacher("熊永康", '男', "数据哭教研");

Console.WriteLine("以下是教师名单:/t");

for (int i = 0; i < t.count; i++)

{

string result = t.getinfo(i);

Console.WriteLine(result);

}

Console.ReadKey();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: