我这里有一个代码片段,但我不理解其中使用"new(code)".
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
Run Code Online (Sandbox Code Playgroud)
具体为什么需要在括号内包含"code"变量.
那是一个构造函数.来自MSDN:类(F#)(请参阅"构造函数"部分):
您可以使用new关键字添加其他构造函数以添加成员,如下所示:
new (argument-list) = constructor-body
在您的示例中,Product类型具有一个接受的默认构造函数,以及一个仅接受code并使用for 的默认构造函数的price附加构造code函数.在这种情况下,括号不是严格要求的,并且代码在没有它的情况下编译相同,尽管如果您希望构造函数采用零参数或多个参数,则需要它.0.0pricecode
等效的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; } }
}
Run Code Online (Sandbox Code Playgroud)