Što je sučelje u C# s primjerom

⚡ Pametni sažetak

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.

  • 🔗 stract: 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.
  • 🔑 Ključna riječ: The interface keyword creates the type, and a class uses a colon to implement it.
  • 🔀 Višestruka sučelja: 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 pomoć: GitHub Copilot scaffolds interfaces and implementations, and ML.NET pipelines rely on interface-based transformer contracts.

Interface in C#

Što je sučelje u C#?

An Sučelje U C# se koristi zajedno s klasom za definiranje 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.

Pogledajmo primjer sučelja mijenjanjem klasa u našoj Konzolnoj aplikaciji. Imajte na umu da nećemo pokretati kod jer ne postoji ništa što se može pokrenuti pomoću sučelja.

Primjer C# sučelja

Napravimo klasu sučelja. Klasa će se zvati "Guru99Interface.” Naša glavna klasa će zatim proširiti definirano sučelje. Sav kod treba biti napisan u datoteci 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 Obrazloženje:-

Ovdje objašnjavamo važne dijelove koda

Primjer C# sučelja

  1. Prvo definiramo sučelje pod nazivom "Guru99Interface.” Imajte na umu da se ključna riječ „interface” koristi za definiranje sučelja.
  2. Zatim definiramo metode koje će koristiti naše sučelje. U ovom slučaju definiramo iste metode koje su korištene u svim ranijim primjerima. Imajte na umu da sučelje samo deklarira metode. Ne definira kod u njima.
  3. Zatim napravimo naše Guru99Tutorial klasa proširuje sučelje. Ovdje pišemo kod koji definira različite metode deklarirane u sučelju. Ova vrsta kodiranja postiže sljedeće
    • Osigurava da razred, Guru99Tutorial dodaje samo kod koji je potreban za metode "SetTutorial" i "GetTutorial" i ništa drugo.
    • Također osigurava da se sučelje ponaša kao prevaratract. The razred mora se pridržavati pravilatracDakle, ako je kontracAko t kaže da bi trebao imati dvije metode pod nazivom "SetTutorial" i "GetTutorial", onda bi tako i trebalo biti.

C# Interface vs Abstract klasa

A common question for beginners is how a C# interface differs from an abstract klasa. Both define a contract that other types follow, yet they serve different design goals.

The key differences are listed below:

  • provedba: 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 abstract klasa.
  • Država: Trbušnjacitract class can hold fields, constructors, and properties with data, whereas an interface cannot store instance state.
  • Access modifiers: Kormilartract class members can be public, protected, or private, while classic interface members are implicitly public.
  • Slučaj upotrebe: 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.

Korak 1) Declare two interfaces, each with its own method.

Korak 2) Create a class that implements both interfaces, separating the interface names with a comma.

Korak 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 Obrazloženje:-

  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.

Kada se program pokrene, ispisuje 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.

Glavne prednosti uključuju:

  • Labava spojka: 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.
  • Testabilnost: Interfaces make it simple to swap a real class for a mock object during unit testing.
  • Ubrizgavanje ovisnosti: Frameworks inject an interface implementation at run time, a core idea behind the SOLID principles.
  • Dosljednost: 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.

Pitanja i odgovori

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.

Sažmite ovu objavu uz: