Is it possible do Declare a constant array that includes another constant array?

后端 未结 4 1650
天涯浪人
天涯浪人 2021-01-21 15:49

I want to do something like this:

const

  MyFirstConstArray: array[0..1] of string = (\'Hi\', \'Foo\');
  MySecondConstArrayWhichIncludesTheFirstOne: array[0..2         


        
相关标签:
4条回答
  • 2021-01-21 16:30

    Actually, you can but do it using records. i use this technique in a big way for creating definitions for certain behaviours of entities in my software. it's a very powerful technique:

    type
          TPerson=record
            // generally you'd put all kinds of addition stuff here including enums, 
            // sets, etc
            saPets:array[0..2] of string;
          end;
    
    const
      scDog='Dog';
    
      MyPeople:array[0..1] of TPerson=
        ((saPets:(scDog, 'Cat', 'Fish'); ),
         (saPets:('Iguana', 'Tarantula', ''); ));
    
    begin
      ShowMessage(MyPeople[0].saPets[0]);
    
    end;
    

    one thing you can't do with it is refer to resource strings. therefore any translation must be done by the code that retrieves the value. i generally index them with enums--in doing so, i can make the software easier to change because it won't compile if i've left something important out.

    0 讨论(0)
  • 2021-01-21 16:33

    AFAIK, you can't do that.
    But if the goal is to ensure you declare your actual constant string only once, I suggest you declare the individual strings and then group them in arrays:

    const
      MyConst1 = 'Hi';
      MyConst2 = 'Foo';
      MyConst3 = 'Bar';
      MyFirstConstArray: array[0..1] of string = (MyConst1, MyConst2);
      MySecondConstArrayWhichIncludesTheFirstOne: array[0..2] of string = 
        (MyConst1, MyConst2, MyConst3);
    

    BTW, your syntax is incorrect, you have to precise the type of the array elements.

    0 讨论(0)
  • 2021-01-21 16:36

    I don't think so. You'll have to do it in code. If these are global constants, you can do the initialization in the 'initialization' section of the unit.

    0 讨论(0)
  • 2021-01-21 16:47

    If order isn't relevant, then use enumerated sets.

    type
      TMyConsts = (tConstFoo, tConstHi, TConstBar);
    const
      MyFirstConstSet = [tConstFoo, tConstHi];
      MySecondConstSet = MyFirstConstSet + [TConstBar];
      MyConstStrings: array[TMyConsts] of string = ('Foo', 'Hi', 'Bar');
    

    You can use the MyConstStrings array to resolve your enumerations into strings if you want. Depends on your objective.

    0 讨论(0)
提交回复
热议问题