概念:
- 所谓泛型,即通过参数化类型来实现在同一份代码上操作多种数据类型。
- 泛型编程是一种编程范式,它利用“参数化类型”将类型抽象化,从而实现更为灵活的复用。
- 使用泛型时,参数化的类型可以设置多个,以逗号隔开。
泛型方法
代码示例:
class Program
{
static void Main(string[] args)
{
Function<int>(1);
Function<string>("a");
Function<char>('.');
Console.ReadKey();
}
static void Function<T>(T t)
{
if (t.GetType()==typeof(int))
{
Console.WriteLine("123");
}
else if (t.GetType() == typeof(string))
{
Console.WriteLine("abc");
}
else
{
Console.WriteLine("……");
}
}
}
--->
123
abc
……
泛型类
代码示例:
class Program
{
static void Main(string[] args)
{
FX<int> fX1 = new FX<int>();
fX1.Function(1);
FX<string> fX2 = new FX<string>();
fX2.Function("a");
FX<char> fX3 = new FX<char>();
fX3.Function('.');
Console.ReadKey();
}
}
class FX<T>
{
public void Function(T t)
{
if (t.GetType() == typeof(int))
{
Console.WriteLine("123");
}
else if (t.GetType() == typeof(string))
{
Console.WriteLine("abc");
}
else
{
Console.WriteLine("……");
}
}
}
--->
123
abc
……
泛型接口
代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace fanxingjiekou
{
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.add(10);
student s = new student();
s.add("你好");
Console.ReadKey();
}
}
interface Ipe<T>
{
void add(T t);
}
class Person : Ipe<int>
{
public void add(int a)
{
Console.WriteLine(a);
}
}
class student : Ipe<string>
{
public void add(string name)
{
Console.WriteLine(name);
}
}
}
--->
10
你好