F#:如何将Json.NET [JsonConstructor]属性应用于主构造函数?

时间:2015-11-25 16:01:16

标签: json f# json.net

我正在尝试在F#中执行某些操作,例如Json.NET documentation中的JsonConstructorAttribute示例:

public class User
{
    public string UserName { get; private set; }
    public bool Enabled { get; private set; }

    public User()
    {
    }

    [JsonConstructor]
    public User(string userName, bool enabled)
    {
        UserName = userName;
        Enabled = enabled;
    }
}

F#中的模拟类似于以下内容,但我在[<JsonConstructor>]的展示位置出错:

[<JsonConstructor>] // ERROR! (see below)
type User (userName : string, enabled : bool) =
    member this.UserName = userName
    member this.Enabled = enabled

错误是

  

此属性无法在此语言元素上使用

那么,我如何用[<JsonConstructor>]装饰主构造函数?

1 个答案:

答案 0 :(得分:6)

事实证明这很容易。通过将[<JsonConstructor>]放在主构造函数的参数列表之前来定位主构造函数:

type User [<JsonConstructor>] (userName : string, enabled : bool) =
    member this.UserName = userName
    member this.Enabled = enabled