Property Indexer

  • Thread starter Thread starter rob
  • Start date Start date
R

rob

You are probably familiar with constructs like:

DataGridView datagridview1;
datagridview1.Columns.DataPropertyName
datagridview1.Columns.Count
datagridview1.Columns.Add(..)

I would like to implement something similar, i.e.

class MyClass
{
public MyProperties....
}
MyClass myClass;
myClass.MyProperties.Prop1
myClass.MyProperties.Count
myClass.MyProperties.Add(..)

How do I go after doing this?

Thanks
 
rob said:
You are probably familiar with constructs like:

DataGridView datagridview1;
datagridview1.Columns.DataPropertyName
datagridview1.Columns.Count
datagridview1.Columns.Add(..)

I would like to implement something similar, i.e.

class MyClass
{
public MyProperties....
}
MyClass myClass;
myClass.MyProperties.Prop1
myClass.MyProperties.Count
myClass.MyProperties.Add(..)

How do I go after doing this?


You have to create your own class (or return a normal ArrayList or
List<T>) and use that as the property.
 
"rob" <[email protected]> a écrit dans le message de (e-mail address removed)...

| You are probably familiar with constructs like:
|
| DataGridView datagridview1;
| datagridview1.Columns.DataPropertyName
| datagridview1.Columns.Count
| datagridview1.Columns.Add(..)
|
| I would like to implement something similar, i.e.
|
| class MyClass
| {
| public MyProperties....
| }
| MyClass myClass;
| myClass.MyProperties.Prop1
| myClass.MyProperties.Count
| myClass.MyProperties.Add(..)
|
| How do I go after doing this?

If you are using VS2005, then follow Jon's advice and use the generic list
classes for list properties, as long as you want users of your class to be
able to do *everything* to the list without restriction.

However, in the case of a Composite list property, when you want to restrict
people from manipulating the list without referring to the owning object,
you need to write your own list manipulation methods in the owning class
e.g.

class InvoiceLine
{
...
}

class Invoice
{
private List<InvoiceLine> lines = new List<InvoiceLine>();

public InvoiceLine Lines[int index]
{
get { return lines[index]; }
}

public int Count
{
get { return lines.Count; }
}

public InvoiceLine AddLine()
{
InvoiceLine newLine = new InvoiceLine();
// set up properites if required
lines.Add(newLine);
return newLine;
}

public void RemoveLine(InvoiceLine line)
{
lines.Remove(line);
}

public void RemoveLineAt(int index)
{
lines.RemoveAt(index);
}
}

This kind of construct is known as Composition; it means that the containing
class is reponsible for managing the lives of the contained item. It is
impossible to add/remove items from the list without using the containing
class's methods.

If you want Aggregation instead, then simply do this :

class MyItem
{
...
}

class MyClass
{
private List<MyItem> items;

public List<MyItem> Items
{
get { return items; }
}
}

Joanna
 
Back
Top