日期:2008-08-24  浏览次数:20903 次

应miles的要求,同时也作为类设计的一个例子,我把我设计日期类的过程整理出来,写成这篇文章,供大家做个参考。也希望这篇文章能抛砖引玉,让大家写出更好,更多的类来。文中有不尽的地方,还请指正。

(一)VBscript自定义类
简单的说,类就是对象,它具有属性和方法。在vbscript里自定义类比C++,JAVA要简单得多。下面将设计一个日期类,用来显示出组合的表单对象。在设计的同时,我们也会说明如何设计自定义类。
1、定义类的语法:class....end class
class及end class用来标识类块的开始和结束,class 标识符后面跟着的是类名称。现在我们把要设计的日期类命名为:dateclass 语法如下:
class dateclass
...
end class

在vbscript中使用些类建立新对象时,可以用new运算符。例如:
set newdate=new dateclass

2、属性和方法:private、public和property
private 用来定义仅能在类内部访问的变量和函数;public则用来定义类的界面,也就是可供外部访问的属性和方法,没有成为 private和public的成员,一律视为public;有和时候,我们要让外部可以访问,但是要指定访问的方法,这时候,就要用property,property语法如下:
public property [let|set|get] aa(...)
...
end property

property 必须和 let、set或get 配合使用。说明如下:
let 设置值,如:user.age=100
set 设置对象,如:set user.myobject=nobject
get 取得值,如:myage=user.age

3、设计日期类的属性和方法
现在我们来设计日期类的属性。为了显示日期,定义一个classdate,来存放日期,它的类型是public,这样可以让用户在类外部改变它;再设计一个函数来显示日期,取名为:datedisplay,类型为public,没有参数。程序如下:
<%
class dateclass

public classdate

public function datedisplay()

end function

end class
%>

4、加入显示日期的代码
现在我们来加入datedisplay的代码,程序如下:
<%
class dateclass

public classdate

public function datedisplay()
'如果没有指定日期,那么设为当前日期
if classdate="" then
classdate=now()
end if
yy=year(classdate)
mm=month(classdate)
dd=day(classdate)
response.write "<input type=text name=yy size=4 maxlength=4 value="&yy&">年"&vbcrlf
response.write "<select name=mm>"&vbcrlf
for i=1 to 12
if i=mm then
response.write "<option value="&i&" selected>"&i&"</option>"&vbcrlf
else
response.write "<option value="&i&">"&i&"</option>"&vbcrlf
end if
next
response.write "</select>月"&vbcrlf
response.write "<select name=dd>"&vbcrlf
for i=1 to 31
if i=dd then
response.write "<option value="&i&" selected>"&i&"</option>"&vbcrlf
else
response.write "<option value="&i&">"&i&"</option>"&vbcrlf
end if
next
response.write "</select>日"&vbcrlf
end function

end class
%>

把上面的代码存为dateclass1.ASP 好了,现在我们已经写好了这个日期类,下面来看看使用的情况
5、调用类 include
在其它程序中使用这个类,只要用include 把dateclass1.ASP包含进来。下面我们写一个测试的程序,文件名为 test1.ASP
<!--#include file="dateclass1.ASP" -->
<%
set newdate= new dateclass
response.write "调用显示:<br>"
newdate.datedisplay
response.write "<br>显示classdate的值:<br>"
response.write newdate.classdate
response.write "<br>设置classdate的值:<br>"
newdate.classdate=cdate("2005/6/15")
'上一句也可以写成:
'newdate.classdate="2005/6/15"
response.write "<br>再调用显示:<br>"
newdate.datedisplay
set newdate=nothing
%>

把两个文件放在同一个目录下,运行test1.ASP 好了,应该已经看到结果了。但是这样的设计还有一些问题:
1、如果用户指定的classdate不是日期型,那么日期就会变成1900年1月1日;
2、如果显示多个日期,表单对象的名字不能是一样的;
3、最好加入CSS;
4、最好还能加入闰年的判断;
5、不是每个月都有31天;
带着这些问题,我们将会继续........