문제

I am trying to set the message formatter for a message in F#. In C# I can have:

    foreach (System.Messaging.Message message in messages)
    {
         message.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
        string body = message.Body.ToString();
        Console.WriteLine(body);
    }

which works just fine. I now want to do the same thing in F# and have:

let mList = messageQueue.GetAllMessages()
let xt = [| "System.String,mscorlib" |]
for m in mList do
    m.Formatter =   XmlMessageFormatter(xt)

which causes this error at compile time:

Error 2 This expression was expected to have type IMessageFormatter
but here has type XmlMessageFormatter

I suspect I am missing a basic concept in F#. What am I doing wrong?

--EDIT-- latkin's answer worked perfectly. Just in case anyone else is interested, here is the full working program in F#:

open System.Messaging

[<EntryPoint>]
let main argv = 
    printfn "%A" argv
    let messageQueue = new MessageQueue(".\private$\Twitter")
    messageQueue.MessageReadPropertyFilter.SetAll();
    let mList = messageQueue.GetAllMessages()
    let xt = [| "System.String,mscorlib" |]
    for m in mList do
        m.Formatter <-  XmlMessageFormatter(xt)
        printfn "%s " (m.Body.ToString())
    0 // return an integer exit code
도움이 되었습니까?

해결책

When you are assigning a mutable value, the operator is <-, not =. In F# = is only used for initial bindings, otherwise it's used as the Boolean equality operator (like C-family ==). Some docs here.

You want

let mList = messageQueue.GetAllMessages()
let xt = [| "System.String,mscorlib" |]
for m in mList do
    m.Formatter <- XmlMessageFormatter(xt)

No casting is needed in this case.

The error comes up because the compiler thinks you are trying to compare a IMessageFormatter to a XmlMessageFormatter.

다른 팁

F# doesn't have implicit casts like C# does, so it doesn't automatically upcast your XmlMessageFormatter to the IMessageFormatter used by the Formatter property.

There was a similar question a couple of days ago with more information about this: F# return ICollection

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top