دلیل استفاده از Indexer چیست؟

hoseng

کاربر بیش فعال
با سلام خدمت همه عزیزانم
میخواستم ببین اصولا مفهوم دقیق Indexer چیه و چرا ازش استفاده میکنیم؟چه فایده ای داره؟
با تشکر :gol:
 

mehrta

عضو جدید
با استفاده از Indexer میتونید جلوی اسم یک آبجکت از اندیس استفاده کنید. با این کار یک متد از شیی فراخوانی میشه و اون اندیس رو به عنوان آرگومان دریافت میکنه و در نهایت یک چیزی رو بر میگردونه. دقیقا مثل آرایه ها رفتار میکنه.




کد:
[COLOR=blue][COLOR=blue]class[/COLOR][COLOR=#222222] TempRecord{ [/COLOR]
[/COLOR][COLOR=green]// Array of temperature values
[/COLOR][COLOR=blue]private[/COLOR] [COLOR=blue]float[/COLOR][] temps = [COLOR=blue]new[/COLOR] [COLOR=blue]float[/COLOR][10] { 56.2F, 56.7F, 56.5F, 56.9F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F };
[COLOR=green]
// Indexer declaration.
[/COLOR][COLOR=green]// If index is out of range, the temps array will throw the exception.
[/COLOR][COLOR=blue]public[/COLOR] [COLOR=blue]float[/COLOR] [COLOR=blue]this[/COLOR][[COLOR=blue]int[/COLOR] index]
{
        [COLOR=blue]get
[/COLOR]       {
               [COLOR=blue]return[/COLOR] temps[index];        
        }
[COLOR=blue]        set[/COLOR]        
        {           
               temps[index] = value;        
         }    
}
}
 

Similar threads

بالا