Delphi编程中的Enums vs Const vs Class Const

Mar*_*ioh 14 delphi

我在ClientDataSet中有一个整数字段,我需要比较一些值,如下所示:

我可以使用const

const
  mvValue1 = 1;
  mvValue2 = 2;

if ClientDataSet_Field.AsInteger = mvValue1 then
Run Code Online (Sandbox Code Playgroud)

或者枚举

TMyValues = (mvValue1 = 1, mvValue2 = 2);

if ClientDataSet_Field.AsInteger = Integer(mvValue1) then
Run Code Online (Sandbox Code Playgroud)

或类const

TMyValue = class
const
   Value1 = 1;
   Value2 = 2;
end;

if ClientDataSet_Field.AsInteger = TMyValues.Value1 then
Run Code Online (Sandbox Code Playgroud)

我喜欢类const方法,但似乎不是delphi的方式,所以我想知道你的想法

Jim*_*eth 12

宣言:

type
  TMyValues = class
    type TMyEnum = (myValue1, myValue2, myValue3, myValue4);
    const MyStrVals: array [TMyEnum] of string =
      ('One', 'Two', 'Three', 'Four');
    const MyIntVals: array [TMyEnum] of integer =
      (1, 2, 3, 4);
  end;
Run Code Online (Sandbox Code Playgroud)

用法:

if ClientDataSet_Field.AsInteger = TMyValues.MyIntVals[myValue1] then
Run Code Online (Sandbox Code Playgroud)

演员通常是我的最后选择.

  • 当使用类 const 方法时,您不需要进行强制转换。感谢您的反馈 (2认同)

Ste*_*eve 11

我不会说类consts不是Delphi方式.最近他们刚刚将它们介绍给Delphi,你在互联网上发现的很多书籍和文章都是在它们推出之前编写的,因此你不会看到它们被广泛使用.许多Delphi开发人员(我会说大多数人)会在Delphi开始使用之前就开始使用Delphi,因此他们不是第一个想到的东西.