zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#接口Interface

c#接口 interface
2023-09-11 14:19:18 时间
using System;

namespace 接口Interface
{
    class Program
    {
        /*
         语法:修饰符 interface 接口名称:继承的接口列表{ 接口内容 }
         定义:接口是一种用来定义程序的协议,它描述可属于任何或结构的一组相关行为。
         举例说明:可以去去其他店铺购买螺丝钉或螺丝帽
         */
        static void Main(string[] args)
        {
            //实例化MyClass类对象
            MyClass myClass = new MyClass();
            //使用派生类对象,实例化接口 IMyInterface
            IMyInterface iMyInterface = myClass;
            //为派生类中的Name属性赋值
            iMyInterface.ID = "123";
            iMyInterface.Name = "接口 interface";
            //调用派生类中的 方法显示定义的属性值
            iMyInterface.ShowInfo();

            Console.ReadKey();
        }

        interface IMyInterface
        {
            //编号(可读可写)
            string ID { get; set; }
            //姓名(可读可写)
            string Name { get; set; }
            //显示定义的编号和姓名
            void ShowInfo();
        }

        private class MyClass : IMyInterface
        {
            private string _id;
            //编号
            public string ID
            {
                get { return _id; }
                set { _id = value; }
            }

           private string _name;
            //姓名
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }
            public void ShowInfo()
            {
                Console.WriteLine($"ID:{ID}");
                Console.WriteLine($"Name:{Name}");
            }
        }
    }
}