gpt4 book ai didi

c# - Akka.NET 可以在 F# 系统中创建 C# actor 吗?

转载 作者:行者123 更新时间:2023-11-30 16:44:22 25 4
gpt4 key购买 nike

我正在尝试使用 F# 系统中的 C# 库中定义的一些 ReceiveActor。我尝试创建非 F# API ActorSystem 但对 system.ActorOf(Props.Create(fun () -> new CSharpActor())) 的调用不起作用说函数参数不兼容。

我在 F# API 页面中也找不到任何关于如何创建在 C# 库中定义的角色的文档。这只是没有完成吗?这通常是一个“糟糕”的设计吗?也就是说,actor 系统应该在库本身中创建吗?

编辑:我在下面玩的代码

C#代码

namespace CsActors {
using Akka.Actor;
using System;

public class CsActor : ReceiveActor {
public CsActor() {
Receive<string>(msg => { Console.WriteLine($"C# actor received: {msg}"); });
}
}

public class CsActorWithArgs : ReceiveActor {
public CsActorWithArgs(string prefix) {
Receive<string>(msg => { Console.WriteLine($"{prefix}: {msg}"); });
}
}
}

F# 脚本

#I @"../build"

#r @"Akka.dll"
#r @"Akka.FSharp.dll"
#r @"CsActors.dll"

open Akka.Actor
open Akka.FSharp
open CsActors

let system = System.create "fcmixed" (Configuration.load())

// fails at runtime with "System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN' to type 'System.Linq.Expressions.NewExpression'."
//let c1 = system.ActorOf(Props.Create(fun _ -> CsActor()))

// works if CsActor has constructor with no arguments
let c2 = system.ActorOf<CsActor> "c2"
c2 <! "foo"

// if actor doesn't have default constructor - this won't compile
//let c3 = system.ActorOf<CsActorWithArgs> "c3"

// Horusiath solution works for actors requiring arguments
let c4 = system.ActorOf(Props.Create(typeof<CsActorWithArgs>, [| box "c4-prefix" |]))
c4 <! "foo"


// Just for fun trying to use suggestion by dumetrulo (couldn't quite get it to work...)
// copied Lambda module from http://www.fssnip.net/ts/title/F-lambda-to-C-LINQ-Expression
//module Lambda =
// open Microsoft.FSharp.Linq.RuntimeHelpers
// open System.Linq.Expressions
// let toExpression (``f# lambda`` : Quotations.Expr<'a>) =
// ``f# lambda``
// |> LeafExpressionConverter.QuotationToExpression
// |> unbox<Expression<'a>>
//let c5 = system.ActorOf(Props.Create(<@ (fun _ -> CsActorWithArgs "c5-prefix") @> |> Lambda.toExpression))
//c5 <! "foo"

最佳答案

Props.Create with 函数不起作用,因为 Props.Create(() => new Actor(a, b))在 C# 中,实际上是接受一个表达式,并将其解构为角色类型和构造函数参数。这是必要的,因为 Props 要求之一是它必须是可序列化的。

您可以做的是使用 Props.Create(typeof<MyActor>, [| box myArg1; box myArg2 |]) 的另一个重载它本质上做同样的事情,只是没有编译类型安全。

话虽如此,如果您只使用 Akkling 会更好或 Akka.FSharp可能时使用 API。

关于c# - Akka.NET 可以在 F# 系统中创建 C# actor 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43620402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com