Covariance और Contravariance
Covariance और contravariance यह नियम हैं कि कब एक type का container किसी संबंधित type के container की जगह ले सकता है, जैसे apples की एक basket fruit की basket गिनी जाए। वे तय करते हैं कि यह swap कब सुरक्षित है।
In this page:
Syntax
interface IProducer<out T> { T Get(); } // covariance: out
interface IConsumer<in T> { void Use(T item); } // contravariance: in
IEnumerable<object> items = new List<string>();
Covariance and Contravariance
Covariance (out T) किसी ज़्यादा derived type वाले generic interface को वहां उपयोग होने देता है जहां एक कम derived type की उम्मीद हो, जैसे IEnumerable<string> को IEnumerable<object> की तरह treat करना।
Contravariance (in T) input positions के लिए विपरीत दिशा में काम करता है, जैसे delegates। ये annotations सिर्फ interfaces और delegates पर लागू होते हैं, classes पर नहीं, और सिर्फ reference types के लिए मायने रखते हैं।
Note:
IEnumerable<T> covariant है, यही वजह है कि आप एक List<string> को कहीं भी पास कर सकते हैं जहां IEnumerable<object> की उम्मीद हो।उदाहरण: Covariance and Contravariance
using System;
using System.Collections.Generic;
class Program
{
static void PrintAll(IEnumerable<object> items)
{
foreach (object item in items)
{
Console.WriteLine(item);
}
}
static void Main(string[] args)
{
List<string> names = new List<string> { "Ana", "Bo" };
PrintAll(names); // covariance: IEnumerable<string> used as IEnumerable<object>
}
}
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. #}
आम गलतियां
List<T>के साथ covariance उपयोग करने की कोशिश करना, जो invariant है; सिर्फIEnumerable<out T>जैसे interfaces इसकी अनुमति देते हैं।in(contravariance) कोout(covariance) के साथ confuse करना।- किसी parameter position पर
out Tउपयोग करना, जिसकी अनुमति नहीं है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: