Skip to main content
 首页 » 编程设计

c#之如何解决类型约束不匹配,C# 到 F#

2024年02月13日18fff_TT

我正在尝试将一些 C# 代码实现为 p2p 应用程序的 F#。我必须承认我对 p2p 实现没有完全理解,我希望它与修复类型问题无关。所有p2p 库是用 C# 实现的。

C# 实现:

public class TestMessage : Message 
{ 
    public string Text { get; set; } 
} 

...

var p = new Peer(); 
p.Subscribe(new Subscription<TestMessage> 
{ 
    Callback = x => Console.WriteLine(x.Text), 
}); 

基本思路是'p'节点现在订阅'TestMessage'类型的消息,然后有一个类似的方法来发布消息。 “订阅”方法的签名是:

void Peer.Subscribe(ISubscription<Message> subscription) 

订阅接口(interface)的定义:

public interface ISubscription<out T> where T : Message 
{ 
    ICachingOptions CachingOptions { get; set; } 
    IContact Contact { get; set; } 
    string EntitySet { get; set; } 
    string Key { get; } 
    string Topic { get; } 
    Type Type { get; } 
 
    void InvokeCallback(Message message); 
    ISerializableSubscription MakeSerializable(); 
    bool PredicateHolds(Message message); 
} 

F# 实现:

type Xmsg(m:string) = 
    inherit Message() 
    member this.Text = m 
 
let sub = Subscription<Xmsg>() 
sub.Callback <- fun (m: Xmsg) -> System.Console.WriteLine(m.Text) 
let p = new Peer() 
p.Subscribe sub 

最后一行导致以下错误:

The type 'Subscription<Xmsg>' is not compatible with the type 'ISubscription<Message>' 

和

Type constraint mismatch. The type  
    Subscription<Xmsg>     
is not compatible with type 
    ISubscription<Message>     
The type 'Subscription<Xmsg>' is not compatible with the type 'ISubscription<Message>' 

我尝试过使用 :> 和 :?> 进行向上转型和向下转型,但没有成功..

当然,我已经尝试寻找解决方案,但是,要么没有解决方案,要么我不明白如何将它们应用于我的问题...

是否有修复方法?或者我应该放弃并为它创建一个 C# 库项目(并使用 F# 中的那个库)? :)

请您参考如下方法:

正如 Ganesh 所说,F# 不支持协方差,这意味着您不能使用 ISubscription<DerivedType>哪里有ISubscription<BaseType>在 F# 代码中需要。但是,对协方差的支持已嵌入到运行时中,因此您可能可以通过一组强制转换来解决此问题:

p.Subscribe(box sub :?> ISubscription<_>) 

在这里你向上转型sub一直到obj然后向下转换为 ISubscription<Message> ,这应该有效。