Multiple Interfaces का उपयोग
कोई class एक साथ कई interfaces के लिए sign up कर सकती है, जैसे कोई student जो choir, chess club, और soccer team सभी में हो। उसे बस हर एक के promises रखने हैं।
In this page:
Syntax
class ClassName : IFirst, ISecond
{
// implement all members of both interfaces
}
Multiple Interfaces
Class inheritance के विपरीत, एक class एक साथ कितने भी interfaces implement कर सकती है, commas से अलग करते हुए। यह एक single type को कई असंबंधित contracts एक साथ satisfy करने देता है। यह multiple-inheritance-जैसा behavior सुरक्षित रूप से achieve करने का C# का तरीका है।
Note:
एक बड़े interface के बजाय कई छोटे, केंद्रित interfaces उपयोग करें — classes के लिए mix and match करना आसान है।
उदाहरण: Multiple Interfaces
using System;
interface IFlyable
{
void Fly();
}
interface ISwimmable
{
void Swim();
}
class Duck : IFlyable, ISwimmable
{
public void Fly() => Console.WriteLine("Duck is flying");
public void Swim() => Console.WriteLine("Duck is swimming");
}
class Program
{
static void Main(string[] args)
{
Duck d = new Duck();
d.Fly();
d.Swim();
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- एक जैसे method name वाले दो interfaces का टकराना और explicit implementation उपयोग न करना।
- किसी एक interface से members implement करना भूल जाना।
- यह मान लेना कि कोई class एक से ज़्यादा classes से inherit कर सकती है जैसे यह कई interfaces implement कर सकती है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: