使用在类中的泛型-特点:
class Program
{
static void Main(string[] args)
{
// 使用一个泛型
Person<int> person = new Person<int>();
person.Show(23);
// 使用多个泛型
Animal<string, uint, char> animal = new Animal<string, uint, char>
{
name = "Dog",
age = 23,
sex = '男'
};
Console.WriteLine(animal.name);
Console.WriteLine(animal.age);
Console.WriteLine(animal.sex);
}
}
class Person<T> {
public T Show(T x)
{
Console.WriteLine(x);
return x;
}
}
class Animal<T, M, D>
{
public T name;
public M age;
public D sex;
}
class Animal<T, M>
{
public T name;
public M age;
}
class Animal
{
public string name;
public uint age;
}
class Dog : Animal
{
}
class Lee : Person<string>
{
}
使用在方法中的泛型-特点:
class Program
{
static void Main(string[] args)
{
Person.Show<string>();
Person.Show<string>("Hello World ~");
Person.Show("Hello World ~");
Console.ReadKey();
}
}
class Person {
public static void Show<T>()
{
Console.WriteLine("Hello World");
}
public static void Show<T>(T x)
{
Console.WriteLine(x);
}
}
使用在接口中的泛型-特点:
interface IUSB<T> {
void Show(T x);
}
class Mouse : IUSB<string> {
public void Show(string x)
{
Console.WriteLine(x);
}
}