Enums vs Const vs Class Const in Delphi programming

后端 未结 6 1900
长情又很酷
长情又很酷 2021-02-19 06:31

I have an integer field in a ClientDataSet and I need to compare to some values, something like this:

I can use const

const
  mvValue1 = 1;
  mvValue2 =          


        
6条回答
  •  执笔经年
    2021-02-19 06:54

    One thing to consider is backwards compatibility - class constants are relatively new to Delphi so if your code has to be sharable with previous versions than they are out.

    I typically use enumerated types, with the difference from yours is that my first enumeration is usually an 'undefined' item to represent NULL or 0 in an int field.

    TmyValues = (myvUndefined, myvDescription1, myvDescription2)
    
    if ClientDataSet_Field.AsInteger = Ord(myvDescription1) then...
    

    To use a little bit of Jim McKeeth's answer - if you need to display to the user a text viewable version, or if you need to convert their selected text into the enumerated type, then an array comes in handy in conjuction with the type:

    const MYVALS: array [TmyValues ] of string = ('', 'Description1', 'Description2');
    

    You can then have utility functions to set/get the enumerated type to/from a string:

    Function MyValString(const pMyVal:TmyValues):string;
    begin
      result := MYVALS[Ord(pMyVal)];
    end;
    
    Function StringToMyVal(const pMyVal:String):TMyValues;
    var i:Integer;
    begin
      result := myvUndefined;
      for i := Low(MYVALS) to High(MYVALS) do
      begin
        if SameText(pMyVal, MYVALS[i]) then
        begin
          result := TMyValues(i);
          break;
        end;
      end;
    end;
    

    Continuing on... you can have scatter routine to set a combo/list box:

    Procedure SetList(const DestList:TStrings);
    begin
      DestList.Clear;
      for i := Low(MYVALS) to High(MYVALS) do
      begin
        DestList.Insert(MYVALS[i]);
      end;
    end;
    

    In code: SetList(Combo1.Items) or SetList(ListBox1.Items)..

    Then if you are seeing the pattern here... useful utility functions surrounding your enumeration, then you add everything to it's own class and put this class into it's own unit named MyValueEnumeration or whaterver. You end up with all the code surrounding this enumeration in one place and keep adding the utility functions as you need them. If you keep the unit clean - don't mix in other unrelated functionality then it will stay very handy for all projects related to that enumeration.

    You'll see more patterns as time goes and you use the same functionality over and over again and you'll build a better mousetrap again.

提交回复
热议问题