C#之接口

接口类Interface1.cs

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

namespace ConsoleApplication1 {

    /*
    接口:属性、方法、事件、所引器 默认为public 但不能包含常数、字段、
    运算符、实例构造函数、析构函数或其他类型、任何种类的静态成员
    不能包含字段
    成员不允许添加访问修饰符 abstract(抽象类)也不行
    不能包含实现成员的任何代码
    实现过程必须在实现接口的类中完成
    接口可实现多重继承
    */
    interface Interface1 {
    //属性
        //1->接口成员不允许有访问修饰符
        //2->接口中不能有字段,属性声明为自动属性
        string Index {
            get;
            set;
        }
     //方法
        //方法不能包含方法体
        void Descreption();
    }
}

对接口实现的类Class1.cs

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

namespace ConsoleApplication1 {
    class Class1:Interface1 {
        private string _index;
        ////实现接口(隐式)
        //public void Descreption() {
        //    Console.WriteLine("接口描述"+this.Index);
        //}
        //public string Index {
        //    get;
        //    set;
        //}

        //接口实现(显式)
        void Interface1.Descreption() {
            Console.WriteLine("接口描述"+ _index);
        }
        string Interface1.Index {
            get {
                return _index;
            }

            set {
                _index = value;
            }
        }
    }
}
 

调用类

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

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args){

            Class1 class1 = new Class1();
            ////隐式的调用(具体类调用)
            //class1.Index = "嘿嘿";
            //class1.Descreption();
            //显式的调用(接口来调用)
            Interface1 interface1 = new Class1();
            interface1.Index = "嘿嘿";
            interface1.Descreption();

            Console.ReadKey();
显式隐式实现方式并存的情况下,接口调用的是显性方法,类对象调用的是隐形方法
当一个类实现的多个接口中具有相同的方法时,用显式方法来专门实现某个接口的方法时就显得非常有用
} } }

 以前写的没一点印象了,下边接着忽悠

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

namespace 接口 {
    class Program {
        static void Main(string[] args) {
            Ijiekouable jiekou = new person();
            jiekou.jikou();

            Console.ReadLine();
        }
    }
    //接口,必须实现
    interface Ijiekouable {
        void jikou();
    }
    class person:Ijiekouable {
        public void jikou() {
            Console.WriteLine("隐式实现接口");
        }
        void Ijiekouable.jikou() {
            Console.WriteLine("显式实现接口");//优先级高
        }
    }
}
原文地址:https://www.cnblogs.com/liuguan/p/5920730.html