C# interface implementation and inheritance

The implementation of the interface is accomplished through the inheritance of the class. A class can only inherit one parent class, but it can inherit any interface.

The following code declares an interface JieKo, which contains two properties IDHE and Name, and a custom method FangFa.

That's it for the preparations.

        interface JieKo
        {
            string ID//Set readable and writable properties
            {
                get;
                set;
            }
            string Name
            {
                get;
                set;
            }
            void FangFa();//Setting method to display the ID and Name defined above
        }

Customize a class Lei, inherit from the interface JieKo, and set the properties and methods that implement the interface to display to the outside world.

 
 
class Lei : JieKo//Create a class to inherit the interface
        {
            string id = "";
            string name="";
            public string ID//Setting to provide access to the outside world
            {
                get
                {
                    return id;
                }
                set
                {
                    id = value;
                }
            }
            public string Name
            {
                get
                {
                    return name ;
                }
                set
                {
                    name  = value;
                }
            }
            public void FangFa()//Set the display format of the defined ID and NAME
            {
                Console.WriteLine("ID:\tNAME:");
                Console.WriteLine(ID +"\t"+Name );
            }
        }
Finally, the class and interface are instantiated at the main entry of the program, the assignment of the property is set, and the method displays the defined property value.

 static void Main(string[] args)
        {
            while (true)
            {
                Lei lei = new Lei();//The next step is to instantiate the class, interface and display the defined property values
                JieKo jieko = lei;
                jieko.ID = "101";
                jieko.Name = "Boss Lin";
                jieko.FangFa();
                Console.WriteLine("Please press any key to continue!!!\n*******************");
                Console.ReadLine();
            }
            
        }   








Check the running result, it is as follows:


! ! ! PS: Except for the final instantiation, etc., other codes are not written in the main entry of the program, so start a new line.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324782921&siteId=291194637