美文网首页
C#-接口与显式接口实现

C#-接口与显式接口实现

作者: 祝你万事顺利 | 来源:发表于2019-08-23 11:41 被阅读0次

    接口

    接口包含类或结构可以实现一组相关功能的定义。

    interface IEquatable<T>
        {
            bool Equals(T obj);
        }
    

    继承IEquatable的类必须实现Equals的方法,IEquatable<T>不提供Equals的实现。
    接口可以包含方法、属性、事件、索引器。 接口不能包含常量、字段、运算符、实例构造函数、终结器或类型。接口成员会自动称为公有成员,不能包含任何访问符。成员也不能是静态成员。

    接口可以从其他接口继承。 类可能通过它继承的基类或通过其他接口继承的接口来多次包含某个接口。 但是,类只能提供接口的实现一次,并且仅当类将接口作为类定义的一部分 (class ClassName : InterfaceName) 进行声明时才能提供。 如果由于继承实现接口的基类而继承了接口,则基类会提供接口的成员的实现。 但是,派生类可以重新实现任何虚拟接口成员,而不是使用继承的实现。

    显示接口实现

    当一个类继承了多个接口的时候,这些接口中包含签名相同的方法,则在此类上实现此成员会导致,这些接口都将此方法作为实现。

    class Program
        {
            static void Main(string[] args)
            {
                SampleClass sc = new SampleClass();
                IControl ctrl = sc;
                ISurface srfc = sc;
    
                sc.Paint();
                ctrl.Paint();
                srfc.Paint();
            }
        }
    
        interface IControl
        {
            void Paint();
        }
    
        interface ISurface
        {
            void Paint();
        }
    
        public class SampleClass:IControl , ISurface
        {
            //Both ISurface.Paint IControl.Paint call this method
            public void Paint()
            {
                Console.WriteLine("Paint method in SampleClass");
            }
        }
    

    但是,如果接口成员实现不同的功能,则会导致接口实现不正确,创建仅通过接口调用且特定于该接口的类成员,则有可能显式实现接口成员。 这可通过使用接口名称和句点命名类成员来完成。

    class Program
        {
            static void Main(string[] args)
            {
                SampleClass sc = new SampleClass();
                IControl ctrl = sc;
                ISurface srfc = sc;
    
                sc.Paint();
                ctrl.Paint();
                srfc.Paint();
            }
        }
    
        interface IControl
        {
            void Paint();
        }
    
        interface ISurface
        {
            void Paint();
        }
    
        public class SampleClass:IControl , ISurface
        {
            //Both ISurface.Paint IControl.Paint call this method
            public void Paint()
            {
                Console.WriteLine("Paint method in SampleClass");
            }
    
            void IControl.Paint()
            {
                Console.WriteLine("ctrl Paint");
            }
    
            void ISurface.Paint()
            {
                Console.WriteLine("srfc Paint");
            }
        }
    

    相关文章

      网友评论

          本文标题:C#-接口与显式接口实现

          本文链接:https://www.haomeiwen.com/subject/vpszsctx.html