public class Dog
{
private string name;
public Dog(string name)
{
this.name = name;
}
public void PrintName()
{
Console.WriteLine(name);
}
/// <summary>
/// 定义泛型方法IsHappy<T>(T target)定义在普通类当中 +
/// 方法名IsHappy+泛型参数T,可以是多个参数可以是一个参数(可以是任何类型,int啊,类啊都行)+
/// 参数名T target
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="target"></param>
public void IsHappy<T>(T target) where T: class//对方法名IsHappy添加约束,只允许类类型,则int型等其他类型会报错
{
Console.WriteLine("Happy:" + target.ToString());
}
}
public class Cat
{
private string name;
public Cat(string name)
{
this.name = name;
}
public void PrintName()
{
Console.WriteLine(name);
}
}
class shit
{
}
class Program
{
static void Main(string[] args)
{
var dog = new Dog("A");
dog.IsHappy<shit>(new shit());//狗看到狗屎很开心
//dog.IsHappy<int>(3);//狗看到数字3很开心,未添加约束时可以生效
//自从添加了约束(public void IsHappy<T>(T target) where T: class),int类型不再可用
dog.IsHappy<Cat>(new Cat("Tom"));//狗看到Tom猫很开心,未添加约束时可以生效
}
}