声明中的C#/F#差异很奇怪,代码在C#中编译,但在F#中没有 [英] Weird C# / F# difference in a declaration, code compiling in C# but not in F#
问题描述
该行是为InfluxDB驱动程序实例化数据点队列:
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>>()
在C#中,它可以毫无问题地进行编译,但是在F#中,我得到了:
in C#, it compiles without problem, but in F#, I get this:
[FS0001]类型'InfluxValueField'与类型'IComparable'不兼容
[FS0001] The type 'InfluxValueField' is not compatible with the type 'IComparable'
在canton7的评论之后,这是两个外部元素的来源:
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
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
InfluxDataPoint: https://github.com/AdysTech/InfluxDB.Client.Net/blob/master/src/DataStructures/InfluxDatapoint.cs
什么会导致它在C#中而不在F#中编译?
What could cause it to compile in C# but not in F#?
这是两个代码示例:
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)
这篇关于声明中的C#/F#差异很奇怪,代码在C#中编译,但在F#中没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!