简体   繁体   中英

Weird C# / F# difference in a declaration, code compiling in C# but not in F#

The line is to instantiate a queue of data points for the InfluxDB driver:

C#

Events = new ConcurrentQueue<InfluxDatapoint<InfluxValueField>>();

F#

let Events = new ConcurrentQueue<InfluxDatapoint<InfluxValueField>>()

in C#, it compiles without problem, but in F#, I get this:

[FS0001] The type 'InfluxValueField' is not compatible with the type 'IComparable'

Following the comment from canton7, here is the source for both external elements:

InfluxValueField: https://github.com/AdysTech/InfluxDB.Client.Net/blob/master/src/DataStructures/InfluxValueField.cs

InfluxDataPoint: https://github.com/AdysTech/InfluxDB.Client.Net/blob/master/src/DataStructures/InfluxDatapoint.cs

What could cause it to compile in C# but not in F#?


Edit:

Here are two code examples:

C#

namespace A
{
    using System.Collections.Concurrent;
    using AdysTech.InfluxDB.Client.Net;

    public class test
    {
        public test()
        {
            var Events = new ConcurrentQueue<InfluxDatapoint<InfluxValueField>>();
        }
    }
}

F#

namespace A

open System.Collections.Concurrent
open AdysTech.InfluxDB.Client.Net

    module B =
        let Events = new ConcurrentQueue<InfluxDatapoint<InfluxValueField>>()

The trick here is to program to interfaces instead of implementations. So use an interface as the generic type parameter, instead of a concrete type.

open AdysTech.InfluxDB.Client.Net
open System.Collections.Concurrent

let events = ConcurrentQueue<IInfluxDatapoint>()
let event1 = InfluxDatapoint<IInfluxValueField>()
let field1a = InfluxValueField(42.99)
let field1b = InfluxValueField("a message")
let event2 = InfluxDatapoint<IInfluxValueField>()
let field2a = InfluxValueField(0.05)

let addEvents () = 
    event1.Fields.Add("amountRequestedUSD", field1a)
    event1.Fields.Add("message", field1b)
    events.Enqueue(event1)
    event2.Fields.Add("someDouble", field2a)
    events.Enqueue(event2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM