This article focuses on how an interface works and its possible applications.
What is an interface?
An interface defines a blueprint for a class or structure. The interface definition looks similar to a class, but nothing is implemented.
The interface defines attributes, methods, events, and indexers, but the interface does not define any of their implementations, just declares
They exist, and the interface does not actually define any function, but defines the way to interact with the class.
What is not an Interface
Interfaces should not be confused by inheritance. They are two very different things. Inheritance defines many implementations and code reuse,
The interface only defines how to communicate with its implementation class. Just like signing a contract, a class must implement interface formulation
Action.
When is the application interface
The interface allows us to create a good layout for how a class is implemented. This is because the interface guarantees that when many
When a component uses the same interface, it allows us to easily alternate the components using the same interface, dynamic programming becomes
Easy.
Create an Interface
You may want to define your own interface many times. An interface is a great tool for measuring software. When you define an interface, it is similar to a class.
As you can see, I don't actually define any features. What I do is to use the functions implemented by the interface class. The interface prefix is usually
Use I, such as IDisposable, IDataReader, and IEnumerable. I'm sure everyone has used this, but I don't know.
There are many commonly used classes to implement these interfaces.
Implementation Interface
Now we know how to create an interface. We will see how to implement an interface for a class.
Or created Interfaces
Because we have defined two methods in the IHelloWorlder interface, we need to determine that we also define these two methods in the class.
We agree that the class implements the methods to be implemented by any interface. If this parameter is not specified, Visual Studio displays the following message:
Definition method:
Public class MyHelloWorld: IHelloWorlder
{
Public void SayHello ()
{
Console. WriteLine ("Hello world! ");
}
Public void SayGoodBye ()
{
Console. WriteLine ("Good Bye World! ");
}
}
Interface
Now we have an implemented interface,
Public void GreetEveryone (IHelloWorlder hw)
{
// Perform whatever logic you wish here
HW. sayhello ();
}
Public void dosomething ()
{
Myhelloworld helloworld = new myhelloworld ();
Greeteveryone (helloworld );
}
If we want to write another class to implement the interface, we can change the dosomething method to use the new class, because
We use the greeteveryone interface, so we do not need to make any changes,