Pregunta

Consider the following record definition and accompanying method:

    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
            }

Calling the Create method as below succeeds:

    //ok
    let r1 = MyRecord.Create(1, 2)
    //ok
    let r2 = MyRecord.Create(1,2,3)

Attempting to use named parameters, either with required or optional parameters however will not compile. For example

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

According to the MSDN docs (http://msdn.microsoft.com/en-us/library/dd233213.aspx)

Named arguments are allowed only for methods, not for let-bound functions, function values, or lambda expressions.

So, based on this, I should be able to used named arguments to execute Create. Is something wrong with my syntax or am I interpreting the rules incorrectly? Is there a way to used named arguments in this context?

¿Fue útil?

Solución

Based on your sample, I would say you have to write MyRecord.Create(a=1, b=2). Or is that a typo in your question?

Otros consejos

This works in VS 2013:

Using:

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 }

Allows you to write:

let v = MyRecord.Create(a = 1, b = 2)

In order to get the syntax you want, you would need to use:

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 }

However, this is going to cause some compiler warnings you may wish to avoid. This could be disabled via #nowarn "49" before your record declaration, or avoided by using a different name for the create arguments.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top