泛型接口
1.泛型
2.泛型接口
3.Where
一. 泛型
[引入]:与传统集合相比,类型更加安全,不需要装箱和拆箱的操作。
1.理解:
2.Eg:
3.泛型集合
1)List<T>
Eg: List<Student> list=new List<Student>();
List.Add(st);
S=list[0];
2)Dictionary<K,V>
Eg: Dictionary<String,Student> students=new Dictionary<String,Student>();
注意:与HashTable的区别
1)对所保存元素做类型约束
2)添加/读取不需要装箱和拆箱
二. 泛型接口
1.IComparable
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main (string[] args)
{
List<Student> student = new List<Student>();
Student stu1 = new Student(4, "kk");
Student stu2 = new Student(3, "mm");
student.Add(stu1);
student.Add(stu2);
student.Sort();
foreach (Student stu in student)
{
Console.WriteLine(stu.name);
}
}
}
class Student:IComparable<Student>
{
public int num;
public string name;
public Student(int num1,string name1)
{
this.num = num1;
this.name = name1;
}
#region IComparable<Student> 成员
int IComparable<Student>.CompareTo(Student other)
{
if (this.num < other.num)
return -1;
else if (this.num == other.num)
return 0;
else
return 1;
}
#endregion
}
}
2.IComparer<T>比较器
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main (string[] args)
{
List<Student> student = new List<Student>();
Student stu1 = new Student(4, "kk");
Student stu2 = new Student(3, "mm");
student.Add(stu1);
student.Add(stu2);
//student.Sort();
//student.Sort(new NameComparer());
student.Sort(new NumComparer());
foreach (Student stu in student)
{
Console.WriteLine(stu.name);
}
}
}
public class Student:IComparable<Student>
{
public int num;
public string name;
public Student(int num1,string name1)
{
this.num = num1;
this.name = name1;
}
#region IComparable<Student> 成员
int IComparable<Student>.CompareTo(Student other)
{
if (this.num < other.num)
return -1;
else if (this.num == other.num)
return 0;
else
return 1;
}
#endregion
}
public class NumComparer:IComparer<Student>
{
#region IComparer<Student> 成员
public int Compare(Student x, Student y)
{
//throw new Exception("The method or operation is not implemented.");
return (x.num.CompareTo(y.num));
}
#endregion
}
public class NameComparer : IComparer<Student>
{
#region IComparer<Student> 成员
public int Compare(Student x, Student y)
{
//throw new Exception("The method or operation is not implemented.");
return (x.name.CompareTo(y.name));
}
#endregion
}
}
3.自定义泛型接口
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class MyMath:InterfaceMe<int>
{
#region InterfaceMe<int> 成员
public int GetNumber()
{
return 3;
}
#endregion
}
interface InterfaceMe<T>
{
T GetNumber();
}
}
作用:接口只需要声明一次,具体用的时候才确定类型,相当于适用所有的类型。
三. Where
引入:有时候我们要限制泛型的使用。不能随意取值
//值类型
interface Interface4<T> where T : struct
{
T GetNumber();
}
//引用类型
interface Interface4<T> where T : class
{
}
//父类约束:where T:父类名