【发布时间】:2012-05-18 04:22:39
【问题描述】:
类:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession)]
public class MainService : IChat
{
IChatCallback ChatCallback = OperationContext.Current.GetCallbackChannel<IChatCallback>();
Chat chat = new Chat(this);
public void ShowChat()
{
chat.Show();
}
public void SendInstantMessage(string user, string message)
{
chat.RaiseMsgEvents(user, message);
ChatCallback.InstantMessage(user, message);
}
}
表格:
public partial class Chat : Form
{
MainService service;
public Chat(MainService service)
{
InitializeComponent();
OnMsgReceivedEvent += new OnMsgReceived(callback_OnMsgReceivedEvent);
this.service = service;
}
private void btnSend_Click(object sender, EventArgs e)
{
service.SendInstantMessage("Admin", txtMsg.Text);
}
}
mainForm 使用这样的类:
public partial class Form1 : Form
{
ServiceHost host;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
host = new ServiceHost(typeof(WCF_Server.MainService));
host.Open();
}
}
在主窗体中,我只是传递类,没有初始化,但是在调用ShowChat()的类中,我需要显示聊天窗体并访问该类方法,以便我可以发送消息。
【问题讨论】:
-
你遇到什么样的错误?
-
@skyfoot 是的,我得到“关键字 'this' 在当前上下文中不可用”
-
您正在尝试从您的构造函数访问
this。this尚未初始化。 -
@MurHafSoz:将
Chat类更改为ChatForm后,您发布的代码将编译。因此,您的代码必须与您发布的不同。 -
@JonSkeet 抱歉,我编辑了代码。