一、系统自带常用的泛型
1.字典,集合
//字典
Dictionary dic = new Dictionary();
//泛型集合
List list = new List();
2.泛型委托,输入参数,输出参数
//泛型 委托---输出参数
Func show = () =>
{
int num = 0;
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
num += i;
}
return num;
};
Console.WriteLine(show()); //执行方法返回结果
//泛型 委托--输入参数
Action go = (num) =>
{
for (int i = 0; i < num; i++)
{
Console.WriteLine(num);
}
};
go(10);//输入参数执行发放,没有返回结果
3.泛型任务,多线程,异步编程
//泛型任务---多线程异步
Task task = Task.Run(() =>
{
return "测试内容";
});
Console.WriteLine(task.Result);
二、泛型方法,使用案例
1. 任意类型数据交换
///
/// 交换任意两个变量的值
///
///
///
///
public static void Swap(ref T arg0,ref T arg1)
{
T temp = arg0;
arg0 = arg1;
arg1 = temp;
}
int num1 = 1;
int num2 = 2;
Swap(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 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
{
///
/// 对象组合
///
///
///
///
public List Add(T arg0, T arg1)
{
List list = new List();
list.Add(arg0);
list.Add(arg1);
return list;
}
///
/// 遍历打印
///
///
public void Foreach(List list)
{
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
使用案例:
MyStudent list1 = new MyStudent();
List result1 = list1.Add(1, 2);
list1.Foreach(result1);
Student stu1 = new Student();
stu1.Age = 10;
Student stu2 = new Student();
stu2.Age = 20;
MyStudent list2 = new MyStudent();
List result2 = list2.Add(stu1,stu2);
list2.Foreach(result2);
更多:
C# 委托、事件、回调 讲解_c# 回调委托-CSDN博客
C# 泛型讲解_泛型基础_C# Generic_c#泛型 命名空间-CSDN博客
C#面向对象_C#面向对象开发开发整理-CSDN博客