我有一个问题,当我去if语句中添加更多“名字”时。我很难看到那里是否准备就绪。因此有更简洁的方式来写这个我可以轻松地看到那些名字都在那里读到了吗?
function TfDB.GetW(name: string) :integer;
begin
result := 0;
if (name = 'Destacker') or (name='Router') or (name = 'Turn Table') Then
result := 57;
if (name = 'Laser Marker') then
result := 66;
if (name = 'SP28')OR(name='Chamber') OR (name = 'CM402') OR (name = 'SP60') then
result := 65;
if (name = 'Conveyor') OR (name = 'Slide Gate') OR (name = 'Washer') then
result := 51;
if (name = 'BTU') OR (name = 'Furukawa') OR (name = 'Radial') OR (name = 'HDP') or (name = 'MSR') OR (name = 'Koki') Or (name = 'MSF') then
result := 98;
if (name = 'Buffer')OR (name = 'Reclaimer') OR (name = 'ECO Roller') then
result := 49;
if (name = 'Inverter') or (name = 'CNC') then
result := 42;
if (name = '3-D Check Station') or (name='Screw Machine') or (name='VT-Win') or(name='Component Viewer') then
result := 58;
if (name = 'AOI Panel') or (name='AirBlow') then
result := 42;
if (name='Mag Loader') or (name='Soltec') then
result := 73;
if (name='Tester') then
result := 33;
if (name='LoadBox') then
result := 17;
if (name = 'DeltaWave') then
result := 89;
if (name = 'ScrewFeeder') then
result := 25;
if (name='Pump') then
result := 33;
//if result is 0 show message error.
end;
答案 0 :(得分:10)
您可以创建字典TDictionary<string, Integer>
,并将其存储在全局变量中。在初始化时将名称加载到宽度映射。然后你的功能变成了一个单行。
var
WidthMapping: TDictionary<string, Integer>;
....
function TfDB.GetW(name: string) :integer;
begin
if not WidthMapping.TryGetValue(name, Result) then
... handle error condition
end;
....
initialization
WidthMapping := TDictionary<string, Integer>.Create;
WidthMapping.Add('Destacker', 57);
WidthMapping.Add('Router', 57);
... etc.
....
finalization
WidthMapping.Free;
答案 1 :(得分:5)
是的,不要使用if
语句,而是使用数组和循环:
const
NAME_RESULT: array [1..2] of record
Name: string;
Value: Integer;
end = (
(Name: 'whatever'; Value: 57)
, (Name: 'Something else'; Value: 57)
);
var
i: Integer;
begin
Result := 0; // or whatever you need your default to be
for i := Low(NAME_RESULT) to High(NAME_RESULT) do
if SameText(name, NAME_RESULT[i].Name) then
begin
Result := NAME_RESULT[i].Value;
Break;
end;
end;
其他优点:您不需要保留返回相同值的名称,但可以按字母顺序对列表进行排序。
答案 2 :(得分:1)
创建一个数组(或动态数组,如果你想进一步添加更多名称,而不需要任何数组维度),包含你想要测试的所有名称的字符串(这里我假设固定大小的字符串数组):
var test = array [1..50] of string;
a[1]:='Destacker';
a[2]:='Router';
等
在您的测试例程中,您可以使用 case 关键字,如下所示:
function TfDB.GetW(index: integer) :integer
begin
result:=0;
case index of
1,2,3: result:=57;
4: result:=66
end
end;
我觉得这样比较容易