课程: C# Practice: Interfaces and Abstract Classes
Solution: Implement an interface
- [Instructor] In C# and .NET interfaces are a powerful tool for creating flexible and scalable code. Let's take a closer look. On line 24 you can see I've declared an interface called ICard. In .NET the naming convention is to always use a capital letter I for any interface, so that's what I've done here. Within my interface, I can define a set of methods, properties, events and indexers. When a class implements this ICard interface, it's signaling to other objects that it supports that interface signature and provides real behavior that is required by the other objects. To meet the code challenge requirements, I've written two properties and one method in the interface. So here's my two properties, CardPrice and Discount and my one method is GetDiscountedPrice. Note that the properties look like normal class properties. It has a getter and a setter. And you'll also note that when I implemented them in TradingCard, they look identical. In that case, I didn't extend or add any additional behavior to these two properties. Now let's take a look at line 26. These look like normal class properties. These, the only difference is there's no scope keyword, like public or private or internal. Up until 2019, when C# 8 was released, you couldn't use scope keywords on interface members. Now we can, so it's possible for me to go up here and mark this with the public keyword. And I'll test the interface, make sure everything's working. We're getting a correct answer over here. Next, let's talk about the interface method. Interface methods traditionally do not contain code. They are similar to abstract methods in that regard. As you can see, there's no code in this declaration, just a signature. So that means that the class that implements the interface must provide the code. And you can see I've done that up here on line 19. It's got the same signature as declared in the interface and then it's actually doing some work. Now, this is a time-honored tradition in object-oriented programming where the interface method does not have any functionality. However, C# 8 changed that. It is now possible to provide a default implementation in the interface. Why have this? Well, it makes it possible to modify an interface after it's been deployed and used by other types, but I'm not using that feature in this code solution. So, that's my solution. Onward to the next code challenge.