interface接口简单用法

接口包含非抽象类或结构必须实现的一组相关功能的定义。 接口可以定义 static 方法,此类方法必须具有实现,按照约定,接口名称以大写字母 I 开头。

接口具有以下属性:
接口通常类似于只有抽象成员的抽象基类。 实现接口的任何类或结构都必须实现其所有成员。 接口可以选择性地定义其部分或全部成员的默认实现。
接口无法直接进行实例化。 其成员由实现接口的任何类或结构来实现。
一个类或结构可以实现多个接口。 一个类可以继承一个基类,还可实现一个或多个接口。

接口调用用法

    class Program
    {
        static void Main(string[] args)
        {
            interfaceA iA = new A();
            iA.AMethod("1234");

            Console.ReadKey();
        }
    }

    public interface interfaceA
    {
       void AMethod(string s);
    }

    public class A:interfaceA
    {
        public void AMethod(string s)
        {
            Console.WriteLine("AMethod " + s);
        }
    }

运行结果
在这里插入图片描述
多接口及继承

   class Program:interfaceB
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.AMethod("A");
            p.BMethod("B");

            Console.ReadKey();
        }

        public void BMethod(string s)
        {
            Console.WriteLine(s);
        }

        public void AMethod(string s)
        {
            Console.WriteLine(s);
        }
    }

    public interface interfaceA
    {
       void AMethod(string s);
    }
    public interface interfaceB:interfaceA
    {
        void BMethod(string s);
    }

运行结果
在这里插入图片描述

在接口中实现事件

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            interfaceA iA = a;
            iA.testEvent += iA_testEvent;

            a.Trigger();

            Console.ReadKey();
        }

        static void iA_testEvent(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

    }

    public interface interfaceA
    {
        event EventHandler testEvent;
    }

    public class A : interfaceA
    {
        public event EventHandler testEvent;

        public void Trigger()
        {
            if (null != testEvent)
            {
                Console.WriteLine("Class A Trigger");
                testEvent(this, EventArgs.Empty);
            }
        }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值