我开始学习C#并且无法弄清楚如何从接口方法中调用基类方法。在这种特殊情况下,我需要以某种方式从sendData
方法中调用onRecieve
。
WebSocketBase.cs
using WebSocketSharp;
using System;
using System.Collections.Generic;
using System.Threading;
class WebSocketBase
{
private WebSocket webSocketClient = null;
private WebSocketService webService = null;
private string url = null;
public WebSocketBase(string url, WebSocketService webService)
{
this.webService = webService;
this.url = url;
}
public void start()
{
webSocketClient = new WebSocket(url);
webSocketClient.OnError += new EventHandler<WebSocketSharp.ErrorEventArgs>(webSocketClient_Error);
webSocketClient.OnOpen += new EventHandler(webSocketClient_Opened);
webSocketClient.OnClose += new EventHandler<WebSocketSharp.CloseEventArgs>(webSocketClient_Closed);
webSocketClient.OnMessage += new EventHandler<MessageEventArgs>(webSocketClient_MessageReceived);
webSocketClient.ConnectAsync();
}
private void webSocketClient_MessageReceived(object sender, MessageEventArgs e)
{
webService.onReceive(e.Data);
}
public void send(string channel)
{
webSocketClient.Send(channel);
}
public void sendData(string data)
{
send("data");
}
}
interface WebSocketService
{
void onReceive(String msg);
}
Logic.cs
class Logic : WebSocketService
{
public void onReceive(string msg)
{
Console.WriteLine("Received message")
}
}
答案 0 :(得分:3)
也许这不是你的意图(评论和我将编辑)但我最简单的方法是扩展基本类型并实现你的界面。
class Logic : WebSocketBase, WebSocketService
{
public void onReceive(string msg)
{
Console.WriteLine("Received message")
// Call method defined in base
sendData(msg);
}
}
答案 1 :(得分:2)
正如其他评论所示,您没有对WebSocketBase类做任何事情。
其他一些风格点:
a)WebSocketService应该是&#34; IWebSocketService&#34;按惯例
b)如果WebSocketBase的唯一目的是成为基类,你应该将它作为抽象的
c)一定要用访问修饰符标记你的类和接口(不仅仅是它们里面的方法)
public interface IWebSocketService
{
void onReceive(String msg);
}
public abstract class WebSocketBase : IWebSocketService
{
...
private void webSocketClient_MessageReceived(object sender, MessageEventArgs e)
{
webService.onReceive(e.Data);
}
public void sendData(string data)
{
send("data");
}
}
public class Logic : WebSocketBase
{
public void onReceive(string msg)
{
Console.WriteLine("Received message")
}
}
答案 2 :(得分:1)
所以看起来你的WebSocketBase
依赖于服务。为什么不让服务知道WebSocketBase
发送消息的内容?
interface WebSocketService
{
void onReceive(WebSocketBase sender, String msg);
}
class Logic : WebSocketService
{
public void onReceive(WebSocketBase sender, string msg)
{
sender.send("blah");
}
}
class WebSocketBase
{
...
private void webSocketClient_MessageReceived(object sender, MessageEventArgs e)
{
webService.onReceive(this, e.Data);
}
public void send(string channel)
{
webSocketClient.Send(channel);
}
...
}