static void ShowInfo(int param)
{
Console.WriteLine($"{param.GetType().FullName}--{param}");
}
static void ShowInfo(string param)
{
Console.WriteLine($"{param.GetType().FullName}--{param}");
}
static void ShowInfo(double param)
{
Console.WriteLine($"{param.GetType().FullName}--{param}");
}
通过观察,便可看出:上面的方法除了操作的数据类型不同外,在功能上是相同的;可以将代码改写成下面形式:
通过将方法声明为泛型方法,无论是预定义类型、用户自定义类型等,都可以共享同一组代码了。
static void ShowInfo<T>(T param)
{
Console.WriteLine($"{param.GetType().FullName}--{param}");
}
class MyStack<T>
{
private int startPointer = 0;
private T[] stackArray;
public void Push(T item)
{
//压栈
}
public T Pop()
{
//弹栈
return stackArray[stackArray.Length-1];
}
}
static void Main(string[] args)
{
//使用int来替代T
MyStack<int> myStack;
//像普通类型创建实例那样,创建Mystack<int>类型实例
myStack = new MyStack<int>();
//调用方法
myStack.Push(11);
int popItem = myStack.Pop();
Console.ReadLine();
}
class Program
{
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Console.WriteLine($"开始:{stopwatch.ElapsedMilliseconds}");
for (int i = 0; i < 1000; i++)
{
ShowInfo(i);
}
Console.WriteLine(stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
Console.WriteLine($"重新开始:{stopwatch.ElapsedMilliseconds}");
for (int i = 0; i < 1000; i++)
{
ShowInfo<int>(i);
}
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Console.ReadLine();
}
static void ShowInfo<T>(T param)
{
Console.WriteLine($"{param.GetType().FullName}--{param}");
}
static void ShowInfo(int param)
{
Console.WriteLine($"{param.GetType().FullName}--{param}");
}
}
运行结果:
//使用where子句,使类型参数T继承ICompare接口,这样parma1便可以使用CompareTo方法了
static bool IsLessThan<T>(T param1, T param2) where T : IComparable
{
return param1.CompareTo(param2) < 0 ? true : false;
}
static bool IsLessThan<T1,T2>(T1 param1, T2 param2) where T1 : struct,IComparable
{
return param1.CompareTo(param2) < 0 ? true : false;
}
static bool IsLessThan<T1, T2>(T1 param1, T2 param2) where T1 : struct, IComparable
where T2 : class
{
return param1.CompareTo(param2) < 0 ? true : false;
}
下面展示一下约束类型的使用(仅为展示用,实际中可能并不会这样写)
static bool IsLessThan<T1, T2>(T1 param1, T2 param2) where T1 : Student, IComparable
where T2 : class,new()
{
return param1.CompareTo(param2) < 0 ? true : false;
}
以上便是对泛型的概念的总结,关于泛型还有很多未总结的知识点,放在后面再写。
原文:https://www.cnblogs.com/bigbosscyb/p/13943210.html