简体   繁体   English

f#类构造函数格式

[英]f# class constructor formatting

I am creating a program that takes an email and converts it into json. 我正在创建一个程序,它接收一封电子邮件并将其转换为json。 In the interest of learning functional languages I thought it would be a good opportunity to learn F#. 为了学习函数式语言,我认为这是学习F#的好机会。 So first off I want a message class that can then easily be serialized into json. 首先,我想要一个可以轻松序列化为json的消息类。 This class will have some members that can be null. 这个类将有一些可以为null的成员。 Because of these optional parameters I am using the following format 由于这些可选参数,我使用以下格式

type Email(from:string, recipient:string, ?cc:string .........) =
    member x.From = from
    member x.Recipient = recipient.....

This class actually has a lot of members as I want to store every piece of information that an email could have. 这个类实际上有很多成员,因为我想存储电子邮件可能拥有的每一条信息。 What happens is if I try to format the constructor myself by splitting it onto multiple lines I get warnings. 如果我尝试通过将构造函数分成多行来设置构造函数,我会收到警告。 How do people make such a gigantic constructor look good in f#? 人们如何在f#中使这样一个巨大的构造函数看起来很好? Is there a better way to do this? 有一个更好的方法吗?

On a similar note, I'm not finding visual studio very helpful for f#, what are other people using to code? 在类似的说明中,我发现视觉工作室对f#非常有帮助,其他人使用什么编码? I think there is a mode for emacs for example... 我认为有一种emacs模式,例如......

There should not be any warnings if all "newlined" parameters start at the same column. 如果所有“newlined”参数都在同一列开始,则不应该有任何警告。 For example: 例如:

type Email(from:string, recipient:string,
           ?cc:string) =
    member x.From = from
    member x.Recipient = recipient

(I personally enjoy using Visual Studio for F#. I doubt there is an IDE with more complete support.) (我个人喜欢使用Visual Studio for F#。我怀疑IDE有更完整的支持。)

As an alternative to creating constructor that takes all properties as parameters, you can also create an object with mutable properties and then specify only those that you want to set in the construction: 作为创建将所有属性作为参数的构造函数的替代方法,您还可以创建具有可变属性的对象,然后仅指定要在构造中设置的对象:

type Email(from:string, recipient:string) =
  member val From = from with get, set
  member val Recipient = recipient with get, set
  member val Cc = "" with get, set
  member val Bcc = "" with get, set

let eml = Email("me@me.com", "you@you.com", Cc="she@she.net")

This is using a new member val feature of F# 3.0. 这是使用F#3.0的新member val功能。 Writing the same in F# 2.0 would be pretty annoying, because you'd have to define getter and setter by hand. 在F#2.0中编写相同内容会非常烦人,因为您必须手动定义getter和setter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM