全部,
我最近一直在涉足一些 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