EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

C#接口

接口

▢ 接口与class类似,但是它只为其成员提供了规格,而没有提供具体的实现

▢ 接口里面的成员都是隐式抽象的

▢ 一个class或struct可以实现多个接口

接口出现的原因

多人协作


接口实例:

public interface  IEnumerator
{
   bool MoveNext();
   object Current{get;}
   void Reset();
}


▢ 接口的成员都是隐式public的,不可以声明访问修饰符

▢ 实现接口对它的所有成员进行public的实现:

internal class Countdown : IEnumerator
    {
        int count = 11;
        public bool MoveNext() => count-->0;
        public object Current => count;
        public void Reset()
        {
            throw new NotSupportedException();
        }
    }

▢ 可以隐式的把一个对象转化成它实现的接口:

IEnumerator e = new Countdown();
while (e.MoveNext())
  Console.WriteLine(e.Current);

输出:

10
9
8
7
6
5
4
3
2
1
0

▢ 虽然Countdown是一个internal的class,但是可以通过把它的实例转化成IEnumerator接口来公共的访问它的成员


接口的扩展

▢ 接口可以继承其它接口

▢ 当接口里面出现签名一样的方法的时候,从第二个方法开始需要显式实现

▢ 当接口里面出现完全一样的方法的时候,实现一次就可以了


实例:

namespace 接口的拓展
{
    public interface IFoo
    {
        void Do();
    }
    public interface IBar
    {
        int Do();
    }

    public class Parent : IFoo, IBar
    {
        public void Do()
        {
            Console.WriteLine("Foo");
        }

        int IBar.Do()
        {
            Console.WriteLine("Bar");
            return 0;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Parent p = new Parent();
            p.Do();
            ((IBar)p).Do();
            Console.Read();
        }
    }
}

输出:

Foo
Bar

This article was last edited at 2020-03-16 21:08:10

* *