我試圖在F#系統中的C#庫中定義一些ReceiveActor
。我試着創建非F#API ActorSystem
,但是調用system.ActorOf(Props.Create(fun() -> new CSharpActor()))
並不能說函數參數不兼容。Akka.NET可以在F#系統中創建C#actor嗎?
我也無法在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"
C#和F#都編譯到IL。它應該和調用任何其他F#庫沒有什麼不同,只要你提供正確的類型和參數等等,一切都應該起作用。 – mason
您可以發佈類型簽名以及確切的錯誤消息。 – s952163
您可能需要將該函數轉換爲C#的合適代理類型 – Foole