Indexer is a new addition in C #, some friends may be confused, some of the things that have been done recently
Often use index, conveniently write a simple example for everyone to see if there are any questions to ask!
This example contains three classes: DataRow, DataItem, Dataitemcollection.
The indexer is used in dataitemcollection.
Using System;
Using System.Collections;
public static void Main (string [] args)
{
DataRow MyDataRow = new DataRow ();
DataItem Mydataitem = new DataItem ("Text", "Value");
DATAROW.DATAITEMS.ADD (Mydataitem);
Console.WriteLine (Mydatarow.dataitems[0]. Text);
}
public class DataRow
{
Public Dataitemcollection Dataitems;
Public DataRow ()
{
Dataitems = new Dataitemcollection ();
}
}
public class DataItem
{
private string _text;
private string _value;
Public DataItem (string text, String value)
{
_text=text;
_value=value;
}
public string Text
{
Get
{
return (_text);
}
Set
{
_text=value;
}
}
public string Value
{
Get
{
return (_value);
}
Set
{
_value=value;
}
}
}
public class Dataitemcollection
{
Private ArrayList _array = new ArrayList ();
public virtual int Count
{
Get
{
Return (_array. Count);
}
}
Public DataItem This[int Index]//where indexer is used
{
Get
{
if (index>=0 && Index<_array. Count)
{
Return ((DataItem) _array[index]);
}
Else
{
throw new Exception ("index Overflow");
}
}
Set
{
if (index>=0 && Index<_array. Count)
{
_array[index]=value;
}
Else
{
throw new Exception ("index Overflow");
}
}
}
public void Add (DataItem item)
{
_array. ADD (item);
}
public void Remove (DataItem item)
{
_array. Remove (item);
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.