views:

132

answers:

2

I come from Java background, where we have data structures with interfaces that if its collection it support certain behaviour, and a set has another.

while programming in Delphi I thed to hit a brick wall when it comes in asking the reflection about the behaviour of items, its very strange. for example this code does not compile

      menuOfSomeKind.Items.Add(t);

where menu of some kind is a component that has Items that contain other sub components, that are the menu entries.

if I want to dynamically edit this, meaning using the add behaviour, it says '[' expected but '.' found.

Could you please clarify this?

+2  A: 

Probably menuOfSomeKind is TMenuItem and not TMainMenu

If you are adding an item to TMenuItem use MenuItem.Add(t);

If you are adding an item to TMainMenu use MainMenu.Items.Add(t);

Bharat
its a custom component made here, that could be inheriting from TMenuItem. AND THAT SOLVED IT. could you explain the behivor of sending diffrent objects add?
none
MainMenu.Items is a property of TMenuItem type.
Bharat
@none: Objects support "Add()" if they explicitly declare function "Add". There is no rule that they do, and if they do they may do so differently. Some may declare a function Add and an indexed property Items[Index] which returns items by index. Others will declare only property Items, but that property will not be indexed, instead, it will return object WHICH in turn will implement both Add and [] (indexed access). End result is that in the second case you can do Items[] and Items.Add. There is no way to tell which case it is other than looking at the docs or code, or trying.
himself
A: 

There's a difference between TMainMenu/TMenu and TMenuItem.

var
  mainMenu: TMainMenu;
  menu: TMenu;
  subMenu: TMenuItem;
begin
  //***** This creates a new root menu
  mainMenu.Items.Add(TMenuItem.Create);

  //***** Essentially the same as mainMenu
  menu.Items.Add(TMenuItem.Create)

  //***** This adds a new submenu to an existing menu
  subMenu.Add(TMenuItem.Create);

  //***** This adds a new submenu to the first submenu of an existing menu
  subMenu.Items[0].Add(TMenuItem.Create);
end;

Note that presented code compiles but will throw exceptions all over the place when run. For starters, none of the local variables are assigned.

Lieven
thank you very much for the example. its a good example.
none