「这是我参与2022首次更文挑战的第39天,活动详情查看:2022首次更文挑战」
C#的缺点:
1:进行拆箱和装箱的过程损耗性能
2:无论什么数据都往集合里放,不利于编译时对代码安全性的检测
3:显示转换会降低代码可读性。
基于以上缺点,C#推出了泛型
1 :泛型( Generic ) 允许您延迟编写类或方法中的编程元素的数据类型的规范,直到实际在程序中使用它的时候。换句话说,泛型允许您编写一个可以与任何数据类型一起工作的类或方法。可以理解为就是C++中的模板。
泛型避免了数据装箱和拆箱的过程,大大的提高了程序的运行效率。
使用命名空间:
using System.Collections.Generic;
泛型类实例:
// 定义一个泛型类
// T标识任意的数据类型(什么代号都可以)
class fanxings<T>
{
// 定义一个数组,类型为T
T[] array;
private int head;
private int tail;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="length">整数型 数组长度</param>
public fanxings(int length)
{
head = 0;
tail = 0;
array = new T[length];
}
/// <summary>
/// 压入泛型
/// </summary>
/// <param name="item"></param>
public void qwer(T item)
{
if ((tail + 1) % array.Length != head)
{
tail = (tail + 1) % array.Length;
array[tail] = item;
}
else
{
throw new Exception("full");
}
}
/// <summary>
/// 取出泛型
/// </summary>
/// <returns></returns>
public T quchu()
{
if (head != tail)
{
head = (head + 1) % array.Length;
return array[head];
}
else
{
throw new Exception("full");
}
}
}
调用实例:
class Program
{
static void Main(string[] args)
{
// 实例化类;
fanxings <int> fan = new fanxings<int>(20);
fan.qwer(1);
fan.qwer(2);
fan.qwer(3);
fan.qwer(4);
fan.qwer(5);
fan.qwer(6);
fan.qwer(7);
for (int i = 0; i < 7; i++)
{
Console.WriteLine(fan.quchu());
}
// 实例化类;
fanxings<string> fansss = new fanxings<string>(20);
fansss.qwer("A");
fansss.qwer("B");
fansss.qwer("C");
fansss.qwer("D");
fansss.qwer("E");
fansss.qwer("F");
fansss.qwer("G");
for (int i = 0; i < 7; i++)
{
Console.WriteLine(fansss.quchu());
}
Console.ReadLine();
}
}
泛型除了可以定义泛型类之外,还可以定义泛型方法,泛型结构体,泛型委托,泛型接口等。
泛型方法实例:
/// <summary>
/// 泛型方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="a"></param>
/// <param name="b"></param>
public static void fasss<T>(ref T a, ref T b)
{
T t;
t = a;
a = b;
b = t;
}
调用
static void Main(string[] args)
{
// 调用泛型方法
int x = 90, y = 90;
fasss<int>(ref x,ref y );
Console.WriteLine("x={0},Y = {1}", x, y); // 输出:x=90,Y = 90
Console.ReadLine();
}
2:泛型的集合类
// 数据类型 先进后出
List <string> student = new List<string>(20);
student.Add("flower");
student.Add("qwe");
student.Add("ccc");
student.Add("ddd");
student.Add("sss");
//student.Add(123); /// 这样写报错
foreach (string item in student)
{
Console.WriteLine(item);
}
// 数据类型 先进先出
Stack<char> str = new Stack<char>();
str.Push('a');
str.Push('b');
str.Push('c');
str.Push('d');
str.Push('e');
foreach (char item in str)
{
Console.WriteLine(item);
}
// 数据类型 queue 先进先出
Queue<bool> b1 = new Queue<bool>();
b1.Enqueue(true);
b1.Enqueue(true);
b1.Enqueue(false);
foreach (bool item in b1)
{
Console.WriteLine(item);
}
// 对象
Queue<object> b3 = new Queue<object>();
b3.Enqueue(3.21f);
b3.Enqueue("sdkjfhhsdfj");
foreach (object item in b3)
{
Console.WriteLine(item);
}
有好的建议,请在下方输入你的评论。
欢迎访问个人博客 guanchao.site
欢迎访问小程序: