文章目录
泛型概述
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _19._1泛型概述
{
class Program
{
static void Main(string[] args)
{
//集合与数组:①长度可以改变②添加数据时不用考虑具体类型,object
List<int> list = new List<int>();
list.Add(2);
list.Add(4);
list.AddRange(new int[] {
1, 2, 3, 4, 5, 6 });
list.AddRange(list);//泛型可以添加自己
list.Insert(3, 100);//在索引为3处插入100
//list.Sort();//从小到大排序
//list.Reverse();//倒叙
for(int i=0;i<list.Count;i++)
{
Console.WriteLine(list[i]);
}
int[] nums = list.ToArray();//将泛型转换成数组
List<int> listTwo = nums.ToList();//nums可以转换成list
Console.ReadKey();
}
}
}
结果:
2
4
1
100
2
3
4
5
6
泛型集合类使用场合概述
自定义泛型类的创建
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _19._3自定义泛型类的创建
{
public class TGeneric<T>//创建泛型类
{
public T Field;
}
class commonlyClass//普通类
{
public T G<T>(T t)//普通方法
{
return t;
}
}
class TGenericTwo<T>//泛型类
{
public T M(T t)//此方法有自己的类型参数列表,为泛型方法
{
return t;
}
}
class Program
{
static void Main(string[] args)
{
TGeneric<string> g = new TGeneric<string>();
g.Field = "51zxw.net";
Console.WriteLine(g.Field);
Console.ReadKey();
}
}
}
类型参数
using System;
using System.Collections.Generic