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

编程入门 行业动态 更新时间:2024-10-27 20:25:38
本文介绍了F#:如何将Json.NET [JsonConstructor]属性应用于主要构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

F#中的类似物似乎类似于以下内容,但在[<JsonConstructor>]的放置位置时出现错误:

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

错误是

此属性不适用于此语言元素

This attribute is not valid for use on this language element

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

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

推荐答案

事实证明,这很简单.通过将[<JsonConstructor>]放在主要构造函数的参数列表之前来定位主要构造函数:

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

更多推荐

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

本文发布于:2023-11-12 09:29:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581111.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用于   如何将   函数   属性   JsonConstructor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!