皆様、
私は最近、いくつかの 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