VB中十七种可用一行代码完成的技巧

发表于:2007-06-21来源:作者:点击数: 标签:
编程要讲效率,尽管现在的计算机,速度是不成问题,但是,如果一行代码能完成,为什么要用更多的代码了? 1、下列代码,则是对逻辑运算不清楚造成。 if a=true then c= not b else c= b end if 可以: c=a xor b 2、如果加上下列代码: if c=true then d=28

   

编程要讲效率,尽管现在的计算机,速度是不成问题,但是,如果一行代码能完成,为什么要用更多的代码了?


1、下列代码,则是对逻辑运算不清楚造成。
if a=true then
   c= not b
else
   c=  b

end if

可以:

c=a xor b

2、如果加上下列代码:

if c=true then
   d=28
else
   d=29  
end if

d=iif((a xor b),28,29)

3、布尔赋值,常被人忽略:

如:

if a= 13 then

 b=true
 
else
 
 b=false    

end if

可以:
b = a = 13
或者:
b = (a = 13)

我更喜欢用后者,这样代码易于看懂。

4、字串有效性检测:

if isnull(strorg) or strorg="" then

可以:

if len(strorg & "")<>0 then

5、字串重复次数

repeatcount=ubound(split(strorg,strfind))

同样,如果要对字串有效性判断:

repeatcount=iif((len(strorg & "")=0), 0, ubound(split(strorg,strfind))

6、有时需要判断字串数组中是否有这一元素,这时最好不用数组,而用分隔符字串

于是: if len(orgstr)= len(replace(orgstr,findstr)) then

则表明,此元素不存在。  

7、对数组初始化:
最好用变体,这样,也是一行语句:
如:


intarr=array(12,28,29,30,31,52,24,60)

注意,此时需要用变量后缀。上面代码,如要定义为长整型,则

intarr=array(12&,28&,29&,30&,31&,52&,24&,60&)

要将intarr 定义为变体

8、判断大小:

intmax = iif((inta > intb), inta, intb)

intmin = iif((inta < intb), inta, intb)

9、按索引的select case

function getchoice(ind as integer)
 getchoice = choose(ind, "speedy", "united", "federal")
end function

10、按表达式的select case(这种转换要求不能有case else的才可以这样,否则会出错)

function matchup (cityname as string)
 matchup = switch(cityname = "london", "english", cityname _
             = "rome", "italian", cityname = "paris", "french")
end function

11、使用iif,前面已有。

function checkit (testme as integer)
 checkit = iif(testme > 1000, "large", "small")
end function

12、字串动态数组是否已初始化

 if len(join(strarr))=0 then
字串动态数组未初始化

13、指定只读combbox的当前值,如果能确认这个值就在其中,一定不会错,则:

 combbox=curvalue
 
 注意,不可以写成:combbox.text=curvalue
 前者实际是写 _default 这个属性,而后者则是写text 因为只读,则会导致错误
 
14、如果有下列代码:

select case combbox.text
case "london"
 call funcstrlang(3)
case "rome"
 call funcstrlang(5)
......
end select  


   则可以用itemdata属性
   即:"london" 的 itemdata=3
       "rome" 的 itemdata=5
   
   于是:
     call funcstrlang(combbox.itendata)

15、如果有下列代码:    

select case combbox.text
case "london"
 call clscity.cityintr_london
case "rome"
 call clscity.cityintr_rome
......
end select  
只要:
callbyname clscity, "cityintr_" & combbox.text, vbmethod

16、复制数组到另一变量中:

 dim iorgarr(30) as integer
 dim idesarr as variant
 ......
 idesarr = iorgarr
 
 即主变体直接取数组指针,则所有元素都复制了过去

17、如果有下列代码:
 do while not rsado.eof
 if len(desstr)<>0 then
 desstr=desstr & vbtab
 end if
 desstr=rsado!rec_id
 rsado.movenext
 loop

 则只要:
 desstr=rsado.getstring()

原文转自:http://www.ltesting.net