F#: How to apply Json.NET [JsonConstructor] attribute to primary constructor?

余生长醉 提交于 2021-02-07 14:34:31

问题


I'm trying to do something in F# like the JsonConstructorAttribute example in the Json.NET documentation:

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;
    }
}

The analog in F# appears to be something like the following, but I'm getting an error on the placement of [<JsonConstructor>]:

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

The error is

This attribute is not valid for use on this language element

So then, how do I decorate the primary constructor with [<JsonConstructor>]?


回答1:


It turns out that it's pretty easy. Target the primary constructor by placing [<JsonConstructor>] just before the primary constructor's parameter list:

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


来源:https://stackoverflow.com/questions/33921059/f-how-to-apply-json-net-jsonconstructor-attribute-to-primary-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!