Τι είναι το Interface στο C# με Παράδειγμα

⚡ Έξυπνη Σύνοψη

Interface in C# defines a contract that specifies which methods and properties a class must implement, without providing the actual code. The implementing class supplies the concrete behavior, enabling loose coupling and multiple inheritance across unrelated types.

  • 🔗 μεtract: An interface declares the method and property signatures that every implementing class must define.
  • No implementation: An interface holds only declarations, so the class writes the actual method code.
  • 🔑 Λέξη-κλειδί: The interface keyword creates the type, and a class uses a colon to implement it.
  • 🔀 Πολλαπλές διεπαφές: One class can implement many interfaces, giving C# a form of multiple inheritance.
  • Interface vs abstract class: Interfaces define behavior only, while abstract classes can also hold shared state and code.
  • 🤖 Βοήθεια AI: GitHub Copilot scaffolds interfaces and implementations, and ML.NET pipelines rely on interface-based transformer contracts.

Interface in C#

Τι είναι το Interface στο C#;

An περιβάλλον λειτουργίας σε C# χρησιμοποιείται μαζί με μια κλάση για να ορίσει ένα contract which is an agreement on what the class will provide to an application. The interface defines what operations a class can perform. An interface declares the properties and methods. It is up to the class to define exactly what the method will do.

Ας δούμε ένα παράδειγμα διεπαφής αλλάζοντας τις κλάσεις στην εφαρμογή Console. Σημειώστε ότι δεν θα εκτελούμε τον κώδικα επειδή δεν υπάρχει τίποτα που να μπορεί να εκτελεστεί χρησιμοποιώντας μια διεπαφή.

Παράδειγμα διεπαφής C#

Ας δημιουργήσουμε μια κλάση διεπαφής. Η κλάση θα ονομάζεται "Guru99Interface.” Η κύρια κλάση μας θα επεκτείνει στη συνέχεια την καθορισμένη διεπαφή. Όλος ο κώδικας πρέπει να γραφτεί στο αρχείο Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
 interface IGuru99Interface
 {
  void SetTutorial(int pID, string pName);
  String GetTutorial();
 }

 class Guru99Tutorial : IGuru99Interface
 {
  protected int TutorialID;
  protected string TutorialName;

  public void SetTutorial(int pID, string pName)
  {
   TutorialID = pID;
   TutorialName = pName;
  }

  public String GetTutorial()
  {
   return TutorialName;
  }

  static void Main(string[] args)
  {
   Guru99Tutorial pTutor = new Guru99Tutorial();

   pTutor.SetTutorial(1,".Net by Guru99");

   Console.WriteLine(pTutor.GetTutorial());

   Console.ReadKey();
  }
 }
}

Code Εξήγηση:-

Εδώ, εξηγούμε τα σημαντικά τμήματα του κώδικα

Παράδειγμα διεπαφής C#

  1. Αρχικά ορίζουμε μια διεπαφή που ονομάζεται "Guru99Διεπαφή." Σημειώστε ότι η λέξη-κλειδί «διεπαφή» χρησιμοποιείται για τον ορισμό μιας διεπαφής.
  2. Στη συνέχεια, ορίζουμε τις μεθόδους που θα χρησιμοποιηθούν από τη διεπαφή μας. Σε αυτή την περίπτωση, ορίζουμε τις ίδιες μεθόδους που χρησιμοποιούνται σε όλα τα προηγούμενα παραδείγματα. Σημειώστε ότι μια διεπαφή απλώς δηλώνει τις μεθόδους. Δεν ορίζει τον κωδικό σε αυτά.
  3. Στη συνέχεια, φτιάχνουμε το δικό μας Guru99Η τάξη tutorial επεκτείνει τη διεπαφή. Εδώ γράφουμε τον κώδικα που ορίζει τις διάφορες μεθόδους που δηλώνονται στη διεπαφή. Αυτό το είδος κωδικοποίησης επιτυγχάνει τα ακόλουθα
    • Εξασφαλίζει ότι η τάξη, GuruΤο 99Tutorial προσθέτει μόνο τον κώδικα που είναι απαραίτητος για τις μεθόδους "SetTutorial" και "GetTutorial" και τίποτα άλλο.
    • Επίσης, διασφαλίζει ότι η διεπαφή συμπεριφέρεται σαν ένα contracτ. Το τάξη πρέπει να τηρεί τον όροtracτ. Έτσι, αν το contracΑν λέει ότι θα πρέπει να έχει δύο μεθόδους που ονομάζονται "SetTutorial" και "GetTutorial", τότε έτσι θα έπρεπε να είναι.

C# Interface vs AbstracΤάξη t

A common question for beginners is how a C# interface differs from an ABStracκατηγορίας t. Both define a contract that other types follow, yet they serve different design goals.

The key differences are listed below:

  • Εφαρμογή: An interface contains only declarations, while an abstract class can provide both abstract members and fully implemented methods.
  • Multiple inheritance: A class can implement many interfaces but can inherit only one abstracτάξη τ.
  • Κατάσταση: Ένας κοιλιακόςtract class can hold fields, constructors, and properties with data, whereas an interface cannot store instance state.
  • Access modifiers: Abstract class members can be public, protected, or private, while classic interface members are implicitly public.
  • Περίπτωση χρήσης: Use an interface to add a capability across unrelated types, and an abstract class to share common code among closely related types.

In short, an interface describes what a class can do, while an abstract class can also define part of how it is done.

How to Implement Multiple Interfaces in C#

Unlike class inheritance, C# allows a single class to implement more than one interface. This is how the language offers a safe form of multiple inheritance without the ambiguity that arises from inheriting several base classes at once.

To implement multiple interfaces, list them after the class name and separate each one with a comma. The class must then define every method declared in each interface it implements.

Βήμα 1) Declare two interfaces, each with its own method.

Βήμα 2) Create a class that implements both interfaces, separating the interface names with a comma.

Βήμα 3) Provide a method body for every member declared in each interface.

The example below shows a Document class that implements both an IReadable and an IWritable interface.

using System;
namespace DemoApplication
{
 interface IReadable
 {
  void Read();
 }
 interface IWritable
 {
  void Write();
 }
 class Document : IReadable, IWritable
 {
  public void Read()
  {
   Console.WriteLine("Reading the document");
  }
  public void Write()
  {
   Console.WriteLine("Writing to the document");
  }
  static void Main(string[] args)
  {
   Document doc = new Document();
   doc.Read();
   doc.Write();
   Console.ReadKey();
  }
 }
}

Code Εξήγηση:-

  1. We declare two interfaces, IReadable and IWritable. Each interface declares a single method without a body.
  2. The Document class lists both interfaces after the colon, separated by a comma, so it agrees to honor both contracts.
  3. The class then defines the Read and Write methods. Skipping either method would cause a compile-time error.
  4. The Main method creates a Document object and calls both methods, proving the class satisfies the two interfaces.

When the program runs, it prints Reading the document on the first line and Writing to the document on the second line. This pattern keeps each contract small and focused, which makes the Document class easier to test and extend.

Advantages of Using Interfaces in C#

Interfaces are widely used in professional C# projects because they make code flexible and easier to maintain. They let you program to a contract rather than to a concrete class.

Τα κύρια πλεονεκτήματα περιλαμβάνουν:

  • Χαλαρή σύζευξη: Code depends on the interface, not a specific class, so an implementation can change without breaking the callers.
  • Multiple inheritance: A class can inherit behavior from several interfaces, which plain class inheritance does not allow.
  • Δυνατότητα δοκιμής: Interfaces make it simple to swap a real class for a mock object during unit testing.
  • Ένεση εξάρτησης: Frameworks inject an interface implementation at run time, a core idea behind the SOLID principles.
  • Συνέπεια: Every implementing class is forced to provide the same set of members, which keeps an API predictable.

Because of these benefits, interfaces sit at the heart of most modern C# design patterns and application frameworks.

Συχνές Ερωτήσεις

By convention, a C# interface name starts with a capital letter I, such as IDisposable or IReadable. The I prefix instantly signals that the type is an interface rather than a class or struct.

Before C# 8.0 an interface held only declarations. From C# 8.0 onward, default interface methods let an interface provide a method body, so older implementations keep working when new members are added.

Explicit implementation names a member with its interface prefix, such as IReadable.Read. The member is then callable only through an interface reference, which avoids name clashes when two interfaces declare the same method.

Yes. An interface can inherit one or more other interfaces. A class that implements the child interface must then define every method from both the child and all inherited parent interfaces.

No. An interface cannot be instantiated directly because it has no implementation. You create an object of a class that implements the interface, then reference that object through the interface type.

Yes. Members of a classic interface are implicitly public, and you cannot add access modifiers to them. The implementing class must also declare the matching members as public.

Yes. GitHub Copilot can scaffold an interface, suggest its method signatures, and generate a class that implements it from a short comment or the interface name, which speeds up contract-first development.

ML.NET relies on interfaces such as ITransformer and IDataView to define its machine learning pipeline. Coding against these interface contracts lets you swap models and data sources without rewriting the surrounding training code.

Συνοψίστε αυτήν την ανάρτηση με: