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

本小妞迷上赌 提交于 2019-12-24 06:06:37

问题


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>>()

回答1:


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)


来源:https://stackoverflow.com/questions/58936062/weird-c-sharp-f-difference-in-a-declaration-code-compiling-in-c-sharp-but-no

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!