c#泛型接口的一个例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleApp8
{
    public interface Ianimal where T:class   //约束T,U只能取class类或派生类
    {
        void a1(T t);
        void a2(U u);//中间没有逗号隔开,以空格隔开
    }
    //定义实体类
    public class Dog1
    {
        public string Content { get; set; }
    }
    public class Dog2
    {
        public string Content { get; set; }
    }
    public class Cat1
    {
        public string Content { get; set; }
    }
    public class Cat2
    {
        public string Content { get; set; }
    }
    //实现泛型接口中的方法
    public class Say1:Ianimal    //继承并调用接口实现方法一
    {
        public void a1(Dog1 D)
        {
            Console.WriteLine(D.Content);
        }
        public void a2(Cat1 C)
        {
            Console.WriteLine(C.Content);
        }
    }
    public class Say2 : Ianimal    //继承并调用接口实现方法二
    {
        public void a1(Dog2 D)
        {
            Console.WriteLine(D.Content);
        }
        public void a2(Cat2 C)
        {
            Console.WriteLine(C.Content);
        }
    }



    class Program
    {
        static void Main(string[] args)
        {
            Dog1 D1 = new Dog1();
            D1.Content = "wow-wow";
            Cat1 C1 = new Cat1();
            C1.Content = "miao-miao";
            Dog2 D2 = new Dog2();
            D2.Content = "汪汪";
            Cat2 C2 = new Cat2();
            C2.Content = "喵喵";

            //创建对象,调用相同接口的不同方法
            Ianimal Is = new Say1(); //实例化Say1类调用接口的方法
            Ianimal Is2 = new Say2();//实例化Say2类调用接口的方法

            Is.a1(D1);
            Is.a2(C1);
            Is2.a1(D2);
            Is2.a2(C2);
        }
    }
}

你可能感兴趣的:(c#泛型接口的一个例子)