c# 泛型(知识整理)
1。什么是泛型
所谓泛型,即通过参数化类型来实现在同一份代码上操作多种数据类型,泛型编程是一种编程范式,它利用“参数化类型”将类型抽象化,从而实现更为灵活的复用。
2.安全性
例1:
代码
public class Person
{
private string name;
private int age;
public string Name
{
set { this.name = value; }
get { return name; }
}
public int Age
{
set { this.age = value; }
get { return age; }
}
public Person()
{
}
public Person(string Name, int Age) //构造函数
{
this.age = Age;
this.name = Name;
}
}
{
private string name;
private int age;
public string Name
{
set { this.name = value; }
get { return name; }
}
public int Age
{
set { this.age = value; }
get { return age; }
}
public Person()
{
}
public Person(string Name, int Age) //构造函数
{
this.age = Age;
this.name = Name;
}
}
在编译不会出错,但是执行的时候ArrayList 会出错。
代码
ArrayList peoples = new ArrayList();
peoples.Add(new Person("成龙", 18));
peoples.Add(new Person("李小龙", 17));
peoples.Add("谁是功夫之王?");
foreach (Person person in peoples)
{
Response.Write(person.Name + "今年" + person.Age + "岁。");
}
List<Person> peoples1 = new List<Person>();
peoples1.Add(new Person("成龙", 18));
peoples1.Add(new Person("李小龙", 17));
// peoples.Add("谁是功夫之王?");
foreach (Person person in peoples1)
{
Response.Write(person.Name + "今年" + person.Age + "岁。");
}
ArrayList peoples = new ArrayList();
peoples.Add(new Person("成龙", 18));
peoples.Add(new Person("李小龙", 17));
peoples.Add("谁是功夫之王?");
foreach (Person person in peoples)
{
Response.Write(person.Name + "今年" + person.Age + "岁。");
}
List<Person> peoples1 = new List<Person>();
peoples1.Add(new Person("成龙", 18));
peoples1.Add(new Person("李小龙", 17));
// peoples.Add("谁是功夫之王?");
foreach (Person person in peoples1)
{
Response.Write(person.Name + "今年" + person.Age + "岁。");
}
例子2:
代码
public class Person1
{
public string Eat()
{
return "吃饭";
}
public virtual string Work()
{
return "工作";
}
}
public class Teacher : Person1
{
public override string Work()
{
return "教书";
}
}
public class Student : Person1
{
public override string Work()
{
return "没有工作,需要上学";
}
}
{
public string Eat()
{
return "吃饭";
}
public virtual string Work()
{
return "工作";
}
}
public class Teacher : Person1
{
public override string Work()
{
return "教书";
}
}
public class Student : Person1
{
public override string Work()
{
return "没有工作,需要上学";
}
}
使用:
代码
//此类型转换不需要显示的进行,因为new返回的对象类型为Student
//Person1是Student的基类
Person1 student = new Student();
//虚方法Work()在子类Student中被重写 [多态的应用]
Response.Write(student.Work());
//使用Object类型的变量去保存Student对象的引用依然不需要进行任何显示的转换
//任何类型均是由System.Object派生而来
Object objStudent = new Teacher();
//将Object类型objStudent转换成其派生类型Student则需要强制类型转换
Teacher studentObj = (Teacher)objStudent;
Response.Write(studentObj.Work());
//Person1是Student的基类
Person1 student = new Student();
//虚方法Work()在子类Student中被重写 [多态的应用]
Response.Write(student.Work());
//使用Object类型的变量去保存Student对象的引用依然不需要进行任何显示的转换
//任何类型均是由System.Object派生而来
Object objStudent = new Teacher();
//将Object类型objStudent转换成其派生类型Student则需要强制类型转换
Teacher studentObj = (Teacher)objStudent;
Response.Write(studentObj.Work());
3。泛型方法
这个可以参考:泛型方法
参考:1.C#泛型讲座(一)知识点