非常遗憾 Delphi 的 case 语句不支持字符串, 但我觉得这也可能是基于效率的考量;
如果非要在 case 中使用字符串, 也不是不可以变通, 这里提供了五种方法.
本例效果图:
代码文件:
--------------------------------------------------------------------------------
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
RadioGroup1: TRadioGroup;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
procedure FormCreate(Sender: TObject,',',');
procedure Button1Click(Sender: TObject,',',');
procedure Button2Click(Sender: TObject,',',');
procedure Button3Click(Sender: TObject,',',');
procedure Button4Click(Sender: TObject,',',');
procedure Button5Click(Sender: TObject,',',');
procedure Button6Click(Sender: TObject,',',');
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses TypInfo; {操作枚举用}
{初始化一个单选组, 用于测试}
procedure TForm1.FormCreate(Sender: TObject,',',');
begin
RadioGroup1.Items.CommaText := 'a,bb,ccc,dddd';
RadioGroup1.ItemIndex := 0;
end;
{这是 case 语句比较常规的用法}
procedure TForm1.Button1Click(Sender: TObject,',',');
begin
case RadioGroup1.ItemIndex of
0: Color := clRed;
1: Color := clYellow;
2: Color := clLime;
3: Color := clBlue;
end;
end;
{方法一: 假如要 case 的字符串的长度不同}
procedure TForm1.Button2Click(Sender: TObject,',',');
var
str: string;
begin
str := RadioGroup1.Items[RadioGroup1.ItemIndex];
case Length(str) of
1 : Color := clRed;
2 : Color := clYellow;
3 : Color := clLime;
4 : Color := clBlue;
end;
end;
{方法二: 假如要 case 的字符串的第一个字母不同, case 是支持字符的}
procedure TForm1.Button3Click(Sender: TObject,',',');
var
str: string;
begin
str := RadioGroup1.Items[RadioGroup1.ItemIndex];
case str[1] of
'a': Color := clRed;
'b': Color := clYellow;
'c': Color := clLime;
'd': Color := clBlue;
end;
end;
{方法三: 借用 TStringList}
procedure TForm1.Button4Click(Sender: TObject,',',');
var
List: TStringList;
str: string;
begin
List := TStringList.Create;
List.Text := RadioGroup1.Items.Text;
str := RadioGroup1.Items[RadioGroup1.ItemIndex];
case List.IndexOf(str) of
0: Color := clRed;
1: Color := clYellow;
2: Color := clLime;
3: Color := clBlue;
end;
List.Free;
end;
{方法四: 借用枚举}
type
TMyEnum = (a, bb, ccc, dddd,',',');
procedure TForm1.Button5Click(Sender: TObject,',',');
var
MyEnum: TMyEnum;
str: String;
begin
str := RadioGroup1.Items[RadioGroup1.ItemIndex];
MyEnum := TMyEnum(GetEnumvalue(TypeInfo(TMyEnum), str),',',');
case MyEnum of
a : Color := clRed;
bb : Color := clYellow;
ccc : Color := clLime;
dddd : Color := clBlue;
end;
end;
{方法五: 利用对比字符串返回的整数, 这种方法并不太可靠, 但在某种情况下会更灵活}
procedure TForm1.Button6Click(Sender: TObject,',',');
var
str: string;
begin
str := RadioGroup1.Items[RadioGroup1.ItemIndex];
case CompareStr(str, 'a') of
0: Color := clRed;
1: Color := clYellow;
2: Color := clLime;
3: Color := clBlue;
end;
end;
end.
关键字词: