初学者的关于‘CASE’的问题(30分)

浮生

Unregistered / Unconfirmed
GUEST, unregistred user!
请问大家,CASE的判断可否用string 做类型,用Integer,char都可以,但我用String 通不过。
如:
buf:string;
…………
case buf of
'!run':begin (用"!run:",不加' '也不行)
…………
end

'@wait':…………
…………
else
…………
end;
 
用String作case语句的判断条件,那是不可能的。见Delphi帮助文档:部分原文引用如下

The case statement provides a readable alternative to complex nested if conditionals. A case statement has the form

case selectorExpression of

caseList1: statement1;
...
caseListn: statementn;
end

where selectorExpression is any expression of an ordinal type (string types are invalid) and each caseList is one of the following:

上面这句话说得很清楚了 ordinal type (序数类型:如整形,枚举类型,char好像要加ord())

但 String 字符串类型不属于序数类型,另外在其他的语言(如 C, C++, Java)中多分支选择语句的判断条件也都是序数类型。
 
但是有折衷的方法!其中一种:写的仓促,你应该明白思路了!
var tmp:tstringlist;
buf:string;
tmp:=tstringlist.create;
tmp.add('!run");
tmp.add('@wait");

case tmp.indexof(buf) of
0:begin (用"!run:",不加' '也不行)
…………
end

0:…………
…………
else
…………
 
参看某期的<程序员杂志>有介绍Case statement 的用法
 
看我的帖子(介绍如何在 case 语句里面使用 string):

http://www.delphibbs.com/delphibbs/dispq.asp?lid=1358621

 
case a of
statement1:...;
statement2:...;
....
end;
case 的变量必须是顺序类型的
string不是顺序类型,不能使用
就如real类型不能作为集合的元素
的道理类似。sjn1978说的就是这个道理
 
呵呵,本人也试过用中文字符做判断条件,但失败后看帮助才知道必须是有序类型的数据

最后只好用数字代替,处理完毕后再用函数转换成中文。

今天打开此问题后突然有一想法,但我未试过:

试将这些条件都定义成枚举类型:

如: MyStr = ('!Run','@Wait','#Cancel')
 
其实许多变通的方法实现,举例:
如果你需要判断的是:'!Run','@Wait','#Cancel'
那么你完全可以
case buf[1] of
'!':
'@':
'#':
end case
 
看看beta的贴子吧,把贴子结了
 
多人接受答案了。
 
顶部