一、系统自带常用的泛型
1.字典,集合
//字典
Dictionary<string, int> dic = new Dictionary<string, int>();
//泛型集合
List<int> list = new List<int>();
2.泛型委托,输入参数,输出参数
//泛型 委托---输出参数
Func<int> show = () =>
{
int num = 0;
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
num += i;
}
return num;
};
Console.WriteLine(show()); //执行方法返回结果
//泛型 委托--输入参数
Action<int> go = (num) =>
{
for (int i = 0; i < num; i++)
{
Console.WriteLine(num);
}
};
go(10);//输入参数执行发放,没有返回结果
3.泛型任务,多线程,异步编程
//泛型任务---多线程异步
Task<string> task = Task.Run(() =>
{
return "测试内容";
});
Console.WriteLine(task.Result);
二、泛型方法,使用案例
1. 任意类型数据交换
/// <summary>
/// 交换任意两个变量的值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="arg0"></param>
/// <param name="arg1"></param>
public static void Swap<T>(ref T arg0,ref T arg1)
{
T temp = arg0;
arg0 = arg1;
arg1 = temp;
}
int num1 = 1;
int num2 = 2;
Swap<int>(ref num1, ref num2);
Console.WriteLine(num1);//打印:2
Console.WriteLine(num2);//打印:1
string str1 = "张三";
string str2 = "lisi";
Swap(ref str1,ref str2);
Console.WriteLine(str1);//打印:lisi
Console.WriteLine(str2);//打印:张三
2. 自定义规则和类型,求和处理
//自定义泛型方法
//自定义求和
//int 类型 相加,decimal类型相加 只计算整数相加,字符串类型 转换成整数相加; 学生类型 年龄相加
//返回整数,字符串
public static T Sum<T>(T arg0, T arg1)
{
if (typeof(T) == typeof(Int32))
{
dynamic num1 = arg0;
dynamic num2 = arg1;
T arg3 = num1 + num2;
return arg3;
}
else if (typeof(T) == typeof(double))
{
dynamic num1 = Convert.ToInt32(arg0);
dynamic num2 = Convert.ToInt32(arg1);
T arg3 = num1 + num2;
return arg3;
}
else if (typeof(T) == typeof(string))
{
dynamic num1 = Convert.ToInt32(arg0);
dynamic num2 = Convert.ToInt32(arg1);
dynamic arg3 = (num1 + num2).ToString();
return arg3;
}
else if (typeof(T) == typeof(Student))
{
Student num1 = arg0 as Student;
Student num2 = arg1 as Student;
dynamic arg3 = new Student();
arg3.Age = num1.Age + num2.Age;
return arg3;
}
return default(T);
}
三、泛型类,自定义泛型类
//自定义泛型类
//定义泛型类,存储列表, 共同行为1 对象+对象 返回数组集合; 共同行为2 传入对象集合,执行打印
public class MyStudent<T>
{
/// <summary>
/// 对象组合
/// </summary>
/// <param name="arg0"></param>
/// <param name="arg1"></param>
/// <returns></returns>
public List<T> Add(T arg0, T arg1)
{
List<T> list = new List<T>();
list.Add(arg0);
list.Add(arg1);
return list;
}
/// <summary>
/// 遍历打印
/// </summary>
/// <param name="list"></param>
public void Foreach(List<T> list)
{
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
使用案例:
MyStudent<int> list1 = new MyStudent<int>();
List<int> result1 = list1.Add(1, 2);
list1.Foreach(result1);
Student stu1 = new Student();
stu1.Age = 10;
Student stu2 = new Student();
stu2.Age = 20;
MyStudent<Student> list2 = new MyStudent<Student>();
List<Student> result2 = list2.Add(stu1,stu2);
list2.Foreach(result2);
更多: