1、泛型类:
using System;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Person
{
public string name;
}
/// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="T"></typeparam>
class TTT<T>
{
public void Swap(ref T t1, ref T t2)
{
T t = default(T);
t = t1;
t1 = t2;
t2 = t;
}
}
class Program
{
static void Main(string[] args)
{
Person p1 = new Person();
p1.name = "xiaoming";
Person p2 = new Person();
p2.name = "abc";
TTT<Person> t = new TTT<Person>();
t.Swap(ref p1, ref p2);
Console.WriteLine("p1 {0}", p1.name);
Console.WriteLine("p2 {0}", p2.name);
}
}
}
2、泛型接口
using System;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleApplication1
{
/// <summary>
/// 泛型接口
/// </summary>
/// <typeparam name="T"></typeparam>
interface Show<T>
{
void Print(T t);
}
/// <summary>
/// 具体类
/// </summary>
class Person
{
public string name;
public int age;
}
/// <summary>
/// 实现接口的类
/// </summary>
class MyShow:Show<Person>
{
public void Print(Person p)
{
Console.WriteLine(p.name + " " + p.age);
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.name = "xiaoming";
p.age = 12;
MyShow ms = new MyShow();
ms.Print(p);
}
}
}
泛型接口,在阅读Promise的时候,发现使用了很多。所以这里举了一个小例子,来说明泛型接口的使用方法。