1、泛型List
//List比较通用方便
Console.WriteLine("----------------------------------泛型List<>------------------------------------");
List<string> strList = new List<string>() {"Ant编程","小程序","语法基础" };
foreach(var Item in strList)
{
Console.WriteLine(Item);
}
List<int> intList = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
foreach (var Item in intList)
{
Console.WriteLine(Item);
}
List<object> objList = new List<object>() { true }; //object是所有类型的父类型,object类型做数据转换的时候有装箱拆箱的操作,有性能损耗,建议少用
2、泛型Dictionary<K,V>键值对
//泛型Dictionary<K,V>键值对
Dictionary<int,string>dictionary= new Dictionary<int, string>();
dictionary.Add(1, "C#基础语法");
dictionary.Add(2, "C#进阶语法");
dictionary.Add(3, "Ant编程");
foreach(var Item in dictionary)
{
Console.WriteLine(Item.Key.ToString()+" "+Item.Value);
}
bool isContains = dictionary.ContainsValue("Ant编程");
dictionary.Remove(1); //移除Key值1对应的值
foreach (var Item in dictionary)
{
Console.WriteLine(Item.Key.ToString() + " " + Item.Value);
}
3、自定义泛型
//自定义泛型(泛型最大的优点是做到了通用)
MyGeneric<string> myGeneric = new MyGeneric<string>("自定义泛型");
myGeneric.Show();
Console.ReadLine();
class MyGeneric<T> //参数可以有多个
{
private T t;
public MyGeneric(T t) //构造方法
{
this.t = t;
}
public void Show()
{
Console.WriteLine(t.ToString());
}
}
4、泛型方法
/// <summary>
/// 静态函数中需要调用静态方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="K"></typeparam>
/// <typeparam name="S"></typeparam>
/// <param name="t"></param>
/// <param name="k"></param>
/// <param name="s"></param>
public static void Show<T,K,S>(T t,K k,S s)
{
Console.WriteLine(t.ToString()+k.ToString()+s.ToString());
}
Show(123456,"123",true); //什么类型都可以!!!泛型最大的优点是做到了通用
5、泛型约束
class Program
{
static void Main(string[] args)
{
Console.WriteLine("------------泛型约束-----------------");
//1、约束——表示T类型只接收带一个无参数的构造函数new T();
//2.struct值类型约束
//3.class引用类型约束
//4.自定义类型约束
//值类型——结构类型struct/int double bool 枚举
//引用类型——数组、类、接口、委托、object、字符串
Student2 student = new Student2();
IStudent istudent = null;
Show(student);
}
public static void Show<T>(T t)
where T:class, new()//new()约束一定要写在最后面,多个的话使用逗号分隔,约束是约束的<>中的内容,基类约束只能放一个且只能放最前面,接口约束可以放多个
{
Console.WriteLine();
}
}
interface IStudent<T>//泛型接口
{ }
interface IStudent//普通接口
{ }
class Student//普通类
{ }
class Student2
{ }
6、协变逆变(略)
总结:
【1】泛型的用处–用来让泛型类、泛型方法、泛型接口、泛型委托这些更通用。
【2】约束
1万+

被折叠的 条评论
为什么被折叠?



