GDAY所有,F#可變的,以永恆
我一直在涉足較晚一些F#和我想出了下面的字符串生成器,我從一些C#代碼移植。它將對象轉換爲字符串,只要它傳遞屬性中定義的正則表達式。它對於手頭的任務可能是過度的,但對於學習目的來說則是如此。
當前BuildString成員使用可變字符串變量updatedTemplate。我一直在絞盡腦汁想辦法解決這個問題,而沒有任何可變對象無濟於事。這使我想到了我的問題。
是否有可能實現沒有任何可變對象的BuildString成員函數?
乾杯,
邁克爾
//The Validation Attribute
type public InputRegexAttribute public (format : string) as this =
inherit Attribute()
member self.Format with get() = format
//The class definition
type public Foo public (firstName, familyName) as this =
[<InputRegex("^[a-zA-Z\s]+$")>]
member self.FirstName with get() = firstName
[<InputRegex("^[a-zA-Z\s]+$")>]
member self.FamilyName with get() = familyName
module ObjectExtensions =
type System.Object with
member this.BuildString template =
let mutable updatedTemplate : string = template
for prop in this.GetType().GetProperties() do
for attribute in prop.GetCustomAttributes(typeof<InputRegexAttribute>,true).Cast<InputRegexAttribute>() do
let regex = new Regex(attribute.Format)
let value = prop.GetValue(this, null).ToString()
if regex.IsMatch(value) then
updatedTemplate <- updatedTemplate.Replace("{" + prop.Name + "}", value)
else
raise (new Exception "Regex Failed")
updatedTemplate
open ObjectExtensions
try
let foo = new Foo("Jane", "Doe")
let out = foo.BuildInputString("Hello {FirstName} {FamilyName}! How Are you?")
printf "%s" out
with | e -> printf "%s" e.Message
乾杯布賴恩和Jon 。我會執行這個摺疊,看看它是如何發生的。就像我在問題中提到的那樣,這純粹是一種學術活動。 – Michael 2009-05-21 22:43:19