f# - 这段代码中使用括号是什么意思

标签 f#

我这里有一个代码片段,但我不明白其中“new(代码)”的用法。

type Product (code:string, price:float) = 
   let isFree = price=0.0 
   new (code) = Product(code,0.0)
   member this.Code = code 
   member this.IsFree = isFree

具体来说为什么需要将“code”变量括在括号内。

最佳答案

这是一个构造函数。来自 MSDN: Classes (F#) (参见“构造函数”部分):

You can add additional constructors by using the new keyword to add a member, as follows:

<em>new (argument-list) = constructor-body</em>

在您的示例中,Product type 有一个默认构造函数,它接受 codeprice ,以及一个仅需要 code 的附加构造函数并应用默认构造函数 0.0对于 price 。在本例中,code 周围的括号并不是严格必需的,并且即使没有它,代码也可以进行相同的编译,尽管如果您想要采用零个参数或多个参数的构造函数,则需要它。

等效的 C# 是这样的:

public class Product
{
    private string code;
    private bool isFree;

    public Product(string code, double price) {
        this.code = code;
        this.isFree = price == 0.0;
    }
    
    public Product(string code) : this(code, 0.0) { }
    
    public string Code { get { return this.code; } }
    public float IsFree { get { return this.isFree; } }
}

关于f# - 这段代码中使用括号是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25299366/

相关文章:

f# - 为什么这个带有成员约束的 F# 代码不能编译?

F# 类型为 `and` 和 Lazy?

caching - F#:尝试内存成员函数在每次调用时重置缓存?

Notepad++ 的F#语法高亮

powershell - 是否可以使用 F# 创建 Windows PowerShell Cmdlet?

constructor - 模式匹配中的部分解构 (F#)

F#:函数和静态成员之间的柯里化(Currying)差异

.net - 将颜色对话框结果解析为画笔

mysql - SQLProvider 不适用于任何数据库类型。没有来自 SqlTypeProvider [F#][macOS] 的类型

.net - F# 中的 OrderBy ThenBy