笔记

万物寻其根,通其堵,便能解其困。
  博客园  :: 新随笔  :: 管理

c# 接口

Posted on 2019-01-14 19:29  草妖  阅读(113)  评论(0)    收藏  举报
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        // interface接口的使用
        interface Aminal
        {
            // 不能使用private,public等修饰,但是默认是public
            void MyCatch();
        }
        class Dog : Aminal
        {
            // 实现接口
            public void MyCatch()
            {
                Console.WriteLine("狗正打算抓老鼠!!!");
            }
        }
        static void Main(string[] args)
        {
            // 使用类来实现调用
            Dog dog1 = new Dog();
            dog1.MyCatch();
            // 也可以使用接口来实现
            Aminal dog2 = (Aminal)dog1;
            dog2.MyCatch();
        }
    }
}

 显示实现接口,实现多个接口导致的冲突问题

using System;
using System.Threading;

namespace ConsoleApplication2
{
    class Program
    {
        interface One1
        {
            void method();
        }
        interface One2
        {
            int method();
        }
        class Method12 : One1, One2
        {
            public void method()
            {
                Console.WriteLine("这是method12类的方法,也是继承One1接口的方法...");
            }
            int One2.method()
            {
                Console.WriteLine("这是One2的接口方法...");
                return 0;
            }
        }
        static void Main(string[] args)
        {
            Method12 wd = new Method12();
            ((One1)wd).method();  // wd.method();
            ((One2)wd).method();
        }
    }
}