BOO大全/自訂屬性

维基教科书,自由的教学读本

上一章:延伸方法 目錄 下一章:自訂Macro


自訂屬性(Attribute)[编辑]

這是一個簡單的自訂屬性(Attribute)範例,它延伸了 Boo's 的 property 屬性。與自訂Macro一樣,命名的慣例是:"屬性名稱"+Attribute。

# nonempty.boo
import Boo.Lang.Compiler
import Boo.Lang.Compiler.Ast

class NonEmptyStringAttribute (PropertyAttribute):
	static preCondition = ast { value is not null and len(value) > 0 }
		
	def constructor(propName as ReferenceExpression):
		super(propName,preCondition.CloneNode())

ast之後的大括號裡面是我們想要用來作為屬性(property)預處理條件的運算式﹔NonEmptyStringAttribute則繼承自PropertyAttribute,以便使用原來PropertyAttribute的功能,然後將 preCondition 作為第二個引數,調用父類別的建構子 - CloneNode 則是表示作 AST 運算式的副本。

接著,就可以在你的專案裡使用了,將上面的 nonempty.boo 編譯為組件後,加入你專案的參照裡,然後編譯:

booc testnonempty.boo -r:nonempty.dll

譯註:這是命令列模式下的使用方法,如果你使用 SharpDevelop,大可直接將 testnonempty.boo 與 nonempty.boo 放到同一個專案下,然後直接編譯。 Ast attributes must be compiled to a separate assembly before they can be used.

喔,忘了附上 testnonempty.boo,這裡是 testnonempty.boo:

class Person:
	[NonEmptyString(Name)]  # line 4
	_name as string
	
	[property(Age)]
	_age as int

	override def ToString():
		return _name
		
p = Person(Name:"john",Age:36)
p.Name = ''   # line 14
print p

輸出結果

Unhandled Exception: System.ArgumentException: precondition
 '(value is not null) and (len(value) > 0)' failed:
   at Person.set_Name(String value) in C:\net\sciboo\examples\prop1.boo:line 4
   at ~Prop1Module.Main(String[] argv) in C:\net\sciboo\examples\prop1.boo:line 14

Getters與預處理條件裡的範例比較看看,這樣的標示法雖然比較不那麼緊密,但是比較能表達出程式的意圖。


上一章:延伸方法 目錄 下一章:自訂Macro