- Defining an interface using the interface keyword
- Interfaces define a group of members but do not implement them directly
- Implementing interfaces
- Any class that implements an interface must implement all of its member methods
- Interfaces cannot be instantiated directly
- Interfaces can contain methods and property declarations and cannot contain fields
- All properties and methods in the interface default to public
- A subclass can inherit one parent class and implement multiple interfaces at the same time
-
1 usingSystem;2 3 namespaceInterfacedemo4 {5 //Food Interface6 Public Interface Food7 {8 //Properties are defined in the interface, and properties are not implemented9 floatPrice {Set;Get; }Ten One //in the interface, define the method A //1. Cannot add access modifiers, default is public - //2. The method in the interface cannot be implemented - voidEat (); the } - Public InterfaceB - { - + } - //Apple class + //Apple inherits from Class A and implements the food interface and the B interface A //3. Once a class implements an interface, it must implement all the members defined in the interface at Public classApple:food, B - { - Public float Price - { - Get - { in return 1.5f; - } to Set + { - This. Price =value; the } * } $ //implements the Eat method in food interfacePanax Notoginseng Public voidEat () - { theConsole.WriteLine ("after eating the apple, HP + ten"); + } A } the + Public classBanana:food, B - { $ Public float Price $ { - Get - { the return 3.8f; - }Wuyi Set the { - This. Price =value; Wu } - } About //implements the Eat method in food interface $ Public voidEat () - { -Console.WriteLine ("after eating the banana, HP +"); - } A } + class Program the { - Static voidMain (string[] args) $ { theApple A =NewApple (); the a.eat (); the the Console.WriteLine (a.price); - in //Polymorphic --Polymorphism using interface implementations theFood B =NewApple (); the b.eat (); About the theBanana ba =NewBanana (); the BA. Eat (); + Console.WriteLine (ba.price); - //4. Can not instantiate interface directly the //Food f = new food ();Bayi } the } the}
"Learning notes" C # interface