Generic Interfaces क्या हैं
एक generic interface एक fill-in-the-type-blank वाली promise list है, जैसे एक job जो cook या driver के लिए हो सकती है। अलग-अलग classes इसे अलग types के साथ उपयोग कर सकती हैं।
In this page:
Syntax
interface IInterfaceName<T>
{
void Add(T item);
T Get();
}
class ClassName<T> : IInterfaceName<T>
{
// implement Add and Get
}
Generic Interfaces
Interfaces भी generic हो सकते हैं, जैसे built-in IComparable<T> या IEnumerable<T>, किसी contract को एक class की तरह type से parameterized होने देते हुए।
IContainer<T> implement करने वाली class implementation के समय चुनी एक specific type T के साथ काम करने के लिए commit करती है। यह interface contracts को object पर निर्भर रहने के बजाय सटीक और type-safe रखता है।
Note:
manual casting से बचने के लिए
IEnumerable जैसे non-generic ancestors से IEnumerable<T> जैसे generic interfaces को प्राथमिकता दें।उदाहरण: Generic Interfaces
using System;
interface IContainer<T>
{
void Add(T item);
T GetFirst();
}
class SingleItemContainer<T> : IContainer<T>
{
private T item;
public void Add(T item)
{
this.item = item;
}
public T GetFirst()
{
return item;
}
}
class Program
{
static void Main(string[] args)
{
IContainer<string> container = new SingleItemContainer<string>();
container.Add("first item");
Console.WriteLine(container.GetFirst());
}
}
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. #}
आम गलतियां
- बिना type argument के किसी generic interface को implement करना, जैसे
class Box : IContainer, जो compile नहीं होता क्योंकिIContainer<T>को अपनाTचाहिए। IContainer<int>औरIContainer<string>को एक ही type मानना, जबकि हर closed generic type एक अलग type है और वे interchangeable नहीं हैं।- यह मान लेना कि किसी
IContainer<Dog>का उपयोग वहां किया जा सकता है जहां एकIContainer<Animal>की उम्मीद हो, जिसकी अनुमति नहीं है जब तक interface variance (out/in) के साथ declared न हो।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: