2017-02-15 64 views
0

我想知道,如何實現與Akka.Net的繼承。我希望基礎演員處理基本消息和處理子消息的子演員。Akka.Net演員的繼承

例如,我有以下層次:

public class BaseMessage 
{ 
    public string Data { get; set; } 
} 

public class ChildMessage : BaseMessage 
{ 
    public string ChildData { get ;set; } 
} 

public abstract class BaseActor : ReceiveActor 
{ 
    private string baseData; 

    public BaseActor() 
    { 
     Receive<BaseMessage>(m => { 
      baseData = m.Data; 
     }); 

     // be aware that adding ReceiveAny handler in base class means that you wont be able to add any handlers in descendant actors 
     // just override Unhandled method 
    } 
} 

public class MyActor : BaseActor 
{ 
    private string myData;  

    public MyActor() 
    { 
     Receive<ChildMessage>(m => { 
     myData = m.ChildData; 

     // obviously BaseActor won't receive BaseMessage 
     // so I should somehow send BaseMessage to it 

     // option 1, not sure will it work 
     BaseMessage baseMessage = m as BaseMessage; 
     Self.Tell(baseMessage); 

     // option 2, definitely should work 
     BaseMessage baseMessage = new BaseMessage { Data = m.Data }; 
     Self.Tell(baseMessage); 
     }); 
    } 
} 

問題是:選項1要發送消息給父演員的工作?

+0

在所有應有的尊重,你爲什麼不試試呢?!放入一些console.logs,啓動一個簡單的控制檯應用程序併發送消息。 – tomliversidge

+0

@tomliversidge當然,發佈後會更新 – bonzaster

回答

0

不幸的是,它不會以這種方式工作,因爲父母會攔截ChildMessage發送給兒童演員。所以,我的解決方案是低於

public class BaseMessage 
{ 
    public string Data { get; set; } 
} 

public class ChildMessage : BaseMessage 
{ 
    public string ChildData { get ;set; } 
} 

public abstract class BaseActor : ReceiveActor 
{ 
    private string baseData; 

    public BaseActor() 
    { 
     Receive<BaseMessage>(m => { 
      ProcessMessage(m); 
     }); 

     // be aware that adding ReceiveAny handler in base class means that you wont be able to add any handlers in descendant actors 
     // just override Unhandled method instead 
    } 

    protected virtual void ProcessMessage(BaseMessage m) 
    { 
     baseData = m.Data; 
    } 
} 


public class MyActor: BaseActor 
{ 
    private string myData;  

    public MyActor() 
    { 
     // no interceptor for ChildMessage here, because parent class has interceptor for BaseMessage and it will handle ChildMessage too 
    } 

    protected override void ProcessMessage(BaseMessage m) 
    { 
     base.ProcessMessage(m); 

     // not qute OOP way, but it works 
     var childMessage = m as ChildMessage; 
     if(childMessage != null) 
     { 
      myData = childMessage.ChildData; 
     } 
    } 
}