F# 使用命名参数使用可选参数调用记录成员

F# 使用命名参数使用可选参数调用记录成员,f#,named-parameters,F#,Named Parameters,考虑以下记录定义和附带方法: type MyRecord = { FieldA : int FieldB : int FieldC : int option FieldD : int option } with static member Create(a,b,?c,?d) = { FieldA = a FieldB = b FieldC = c

考虑以下记录定义和附带方法:

    type MyRecord = {
    FieldA : int
    FieldB : int
    FieldC : int option
    FieldD : int option
    } with
        static member Create(a,b,?c,?d) = {
            FieldA = a
            FieldB = b
            FieldC = c
            FieldD = d
            }
按如下方式调用Create方法成功:

    //ok
    let r1 = MyRecord.Create(1, 2)
    //ok
    let r2 = MyRecord.Create(1,2,3)
尝试使用命名参数(无论是必需参数还是可选参数)将无法编译。比如说

    //Compilation fails with a message indicating Create requires four arguments
    let r2 = MyRecord.Create(FieldA = 1, FieldB =2)
根据MSDN文件()

命名参数仅允许用于方法,不允许用于let绑定函数、函数值或lambda表达式


因此,基于此,我应该能够使用命名参数来执行Create。是我的语法有问题还是我对规则的解释有误?有没有一种方法可以在这种上下文中使用命名参数?

根据您的示例,我认为您必须编写
MyRecord.Create(a=1,b=2)
。或者这是你问题中的一个输入错误?

根据你的示例,我认为你必须编写
MyRecord.Create(a=1,b=2)
。还是你的问题有误?

这在VS 2013中有效:

使用:

type MyRecord = 
    {
        FieldA : int
        FieldB : int
        FieldC : int option
        FieldD : int option
    }
    with
        static member Create(a,b,?c : int,?d : int) = 
            { FieldA = a; FieldB = b; FieldC = c; FieldD = d }
允许您编写:

let v = MyRecord.Create(a = 1, b = 2)
为了获得所需的语法,您需要使用:

type MyRecord = 
    {
        FieldA : int
        FieldB : int
        FieldC : int option
        FieldD : int option
    }
    with
        static member Create(FieldA, FieldB, ?FieldC, ?FieldD) = 
            { FieldA = FieldA; FieldB = FieldB; FieldC = FieldC; FieldD = FieldD }
但是,这将导致一些您可能希望避免的编译器警告。这可以在记录声明之前通过
#nowarn“49”
禁用,也可以通过为创建参数使用不同的名称来避免。

这适用于VS 2013:

使用:

type MyRecord = 
    {
        FieldA : int
        FieldB : int
        FieldC : int option
        FieldD : int option
    }
    with
        static member Create(a,b,?c : int,?d : int) = 
            { FieldA = a; FieldB = b; FieldC = c; FieldD = d }
允许您编写:

let v = MyRecord.Create(a = 1, b = 2)
为了获得所需的语法,您需要使用:

type MyRecord = 
    {
        FieldA : int
        FieldB : int
        FieldC : int option
        FieldD : int option
    }
    with
        static member Create(FieldA, FieldB, ?FieldC, ?FieldD) = 
            { FieldA = FieldA; FieldB = FieldB; FieldC = FieldC; FieldD = FieldD }
但是,这将导致一些您可能希望避免的编译器警告。这可以在记录声明之前通过
#nowarn“49”
禁用,也可以通过为create参数使用不同的名称来避免