Another way to achieve abstraction in C#, is with interfaces.
An interface
is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies):
// interface
interface Animal
{
void animalSound(); // interface method (does not have a body)
void run(); // interface method (does not have a body)
}
It is considered good practice to start with the letter "I" at the beginning of an interface, as it makes it easier for yourself and others to remember that it is an interface and not a class.
By default, members of an interface are abstract
and public
.
Note: Interfaces can contain properties and methods, but not fields.
To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class. To implement an interface, use the :
symbol (just like with inheritance). The body of the interface method is provided by the "implement" class. Note that you do not have to use the override
keyword when implementing an interface:
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
abstract
and public
1) To achieve security - hide certain details and only show the important details of an object (interface).
2) C# does not support "multiple inheritance" (a class can only inherit from one base class). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!