f#:如何在类型中定义计算属性?



在c#中,我可以这样定义计算属性:

public class MyViewModel
{
public DateTime StartDate { get; set; }
public string StartDateFormatted => StartDate.ToString("yyyy.MM.dd h:mm tt");
}

我如何在f#中做到这一点?

[<DataContract>]
[<CLIMutable>]
type MyViewModel = {
[<DataMember>] StartDate            : DateTime
[<DataMember>] StartDateFormatted   : string // How can I make this a computed property?
}

在f#:

中非常相似
open System
type MyViewModel() =
member val StartDate = DateTime.Now
member this.StartDateFormatted =
this.StartDate.ToString("yyyy.MM.dd h:mm tt")
let model = MyViewModel()
printfn "%A" model.StartDateFormatted   // "2022.04.27 2:56 tt"

注意,我使用了f#的对象语法来定义类型,而不是它的记录语法。这更接近于你熟悉的c#。

如果你想使用一个记录类型,它看起来就像这样:

type MyViewModel =
{
mutable StartDate : DateTime
}
member this.StartDateFormatted =
this.StartDate.ToString("yyyy.MM.dd h:mm tt")
let model = { StartDate = DateTime.Now }
printfn "%A" model.StartDateFormatted

请注意,记录在默认情况下是不可变的,因此通常不用于视图模型(在MVVM设计中,视图模型会更新以跟踪UI中的更改)。

最新更新