我这里有一个代码片段,但我不明白其中“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 有一个默认构造函数,它接受 code
和price
,以及一个仅需要 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/