Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Trying To Understand Indexers
Message
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Divers
Thread ID:
01433919
Message ID:
01433959
Vues:
44
Hi,
Not sure what you are trying to achieve here but:
(a) the usage will be confusing since cust[0] will refer to an Invoice
(b) you can't add to a list via an indexer so 'cust[0] = InvA;' will fail on an empty list.

Here's a simple example that shows one way an indexer can be helpful:
public class InvoiceList
    {
        List<Invoice> Invoices = new List<Invoice>();

        //Add a Couple of dummy Invoices:
        public InvoiceList()
        {
            Invoices.Add(new Invoice(){Id="A123"});
            Invoices.Add(new Invoice(){Id="B345"});
        }

        public Invoice this[string s]
        {
            get
            {
                Invoice i = Invoices.Find(x => x.Id == s);
                return i;
            }
        }
    }

    public class Invoice
    {
        public string Id { get; set; }
    }
Given this you can access an Invoice using the Id as an indexer. e.g.:
InvoiceList l = new InvoiceList();
Invoice v = l["A123"];
>I have this customer class:
>
>
>public class Customer
>{
>    private List<Invoice> _Invoices = new List<Invoice>();
>    public Invoice this[int item]
>    {
>        get
>        {
>            return _Invoices[item];
>        }
>        set
>        {
>            _Invoices[item] = value;
>        }
>    }
>}
>
>
>I then do this:
>
>
>static void Main(string[] args)
>{
>    Invoice InvA = new Invoice();
>    InvA.InvoiceId = "A0001";
>
>    Invoice InvB = new Invoice();
>    InvB.InvoiceId = "B0002";
>
>    Customer cust = new Customer();
>    cust[0] = InvA;
>    cust[1] = InvB;
>}
>
>
>I'm not really seeing a usage for indexers. It seems to me that an Invoices collection would be better. What's the point of indexers?
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform