从第 2.0.0.8 版开始,X# 也支持 Xbase++ 风格的类声明。当然,我们还在语言定义中添加了强类型,以使代码运行更快。
完整的文档将包含在之后某一个版本中。
下面的代码展示了 Xbase++ 支持的实际效果
CLASS Developer
class var list as array // 类变量就像静态变量。
class VAR nextid as int
class var random as Random
PROTECTED:
VAR id as int NOSAVE // Nosave 子句将用 [NonSerialized] 属性标记字段
EXPORTED:
VAR FirstName as string
VAR LastName as string
VAR Country as string
// 在类...endclass 块中声明方法时,需要使用下一行中的内联前缀。
INLINE METHOD initClass() // 静态构造函数的 Xbase++ 等价物
list := {}
nextid := 1
random := Random{}
RETURN
INLINE METHOD Init(cFirst as string , cLast as string, cCountry as string) // Init 是构造函数
// 你可以使用 :: 替代 SELF:
::FirstName := cFirst
::LastName := cLast
::Country := cCountry
::id := nextid
nextid += 1
aadd(list, SELF)
RETURN
INLINE Method SayHello() as STRING
if ::Age < 40
RETURN "Hello, I am " + ::FirstName+ " from "+::Country
else
RETURN "Hello, I am mr " + ::LastName+ " from "+::Country+" but you can call me "+::FirstName
endif
INLINE METHOD FullName() as string
RETURN ::FirstName + " " + ::LastName
INLINE METHOD Fire() as logic
local nPos as dword
nPos := Ascan(list, SELF)
if nPos > 0
aDel(list, nPos)
ASize(list, aLen(list)-1)
return true
endif
return false
// 下一个代码块包含前向声明。方法必须在类的下面声明...... endclass 块
// SYNC 方法确保只有一个线程可以同时运行这段代码
SYNC METHOD LivesIn
// ACCESS 表示 PROPERTY GET
// ASSIGN 表示 PROPERTY SET
ACCESS CLASS METHOD Length as dword
ACCESS METHOD Age as int
ENDCLASS
// 这就是 LivesIn. 此处不必重复 SYNC
METHOD LivesIn(cCountry as string) as logic
return lower(::Country) == lower(cCountry)
// 这是 AGE 属性的实现。ACCESS 不必在此重复
METHOD Age() as int
local nAge as int
nAge := random:@@Next(25,60)
return nAge
// 这是 Length 属性的实现。ACCESS 不必重复。但必须指定 CLASS。
CLASS METHOD Length as dwor
return ALen(list)
// 入口点是 Main(),就像在 Xbase++ 中一样
function Main(a) as int
local oDeveloper as Developer
local aDevs := {} as array
local i as int
if PCount() > 0
? "Parameters"
for i := 1 to PCount()
? _GetFParam(i)
next
endif
// 用 Xbase++ 语法创建一个新对象。Developer{} 也可以。
aadd(aDevs, Developer():New("Chris", "Pyrgas", "Greece"))
aadd(aDevs, Developer():New("Nikos", "Kokkalis","Greece"))
aadd(aDevs, Developer():New("Fabrice", "Foray","France"))
aadd(aDevs, Developer():New("Robert", "van der Hulst","The Netherlands"))
? "# of devs before", Developer.Length
for i := 1 to alen(aDevs)
oDeveloper := aDevs[i]
? "Fields", oDeveloper:FirstName, oDeveloper:LastName, oDeveloper:Country
? "FullName",oDeveloper:FullName()
? oDeveloper:SayHello()
? "Greece ?", oDeveloper:LivesIn("Greece")
? "Fired", oDeveloper:Fire()
? "# of devs after firing", oDeveloper:FirstName, Developer.Length
next
_wait()
RETURN PCount()