问题
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