问题描述
|
我正在尝试从WCF对象中修改属于Form2的TextBox。
namespace server2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private ServiceHost duplex;
private void Form2_Load(object sender,EventArgs e) /// once the form loads,create and open a new ServiceEndpoint.
{
duplex = new ServiceHost(typeof(ServerClass));
duplex.AddServiceEndpoint(typeof(IfaceClient2Server),new NetTcpBinding(),\"net.tcp://localhost:9080/service\");
duplex.open();
this.Text = \"SERVER *on-line*\";
}
}
class ServerClass : IfaceClient2Server
{
IfaceServer2Client callback;
public ServerClass()
{
callback = OperationContext.Current.GetCallbackChannel<IfaceServer2Client>();
}
public void StartConnection(string name)
{
var myForm = Form.ActiveForm as Form2;
myForm.textBox1.Text = \"Hello World!\"; /// <- this one trows “System.NullReferenceException was unhandled”
/// unless Form2 is selected when this fires.
callback.Message_Server2Client(\"Welcome,\" + name );
}
public void Message_Cleint2Server(string msg)
{
}
public void Message2Client(string msg)
{
}
}
[ServiceContract(Namespace = \"server\",CallbackContract = typeof(IfaceServer2Client),SessionMode = SessionMode.required)]
public interface IfaceClient2Server ///// what comes from the client to the server.
{
[OperationContract(IsOneWay = true)]
void StartConnection(string clientName);
[OperationContract(IsOneWay = true)]
void Message_Cleint2Server(string msg);
}
public interface IfaceServer2Client ///// what goes from the sertver,to the client.
{
[OperationContract(IsOneWay = true)]
void AcceptConnection();
[OperationContract(IsOneWay = true)]
void RejectConnection();
[OperationContract(IsOneWay = true)]
void Message_Server2Client(string msg);
}
}
然而,\“ myForm.textBox1.Text = \” Hello world!\“; \”行引发了System.NullReferenceException未被处理\“ ...
任何想法,谢谢!
解决方法
正如最初问题的注释中所讨论的那样,问题在于您要使用的ActiveForm是您想要的表单未处于活动状态。每当尝试使用
as
关键字进行强制转换时,如果强制转换无效,结果将为null。由于您获取了无法转换为Form2的表单(因为它是另一种表单),因此您正确地收到了null引用异常。
假设您在Form2上执行了单例规则,并且没有使用表单的名称,则可以通过Application.OpenForms集合来访问它,如下所示:
(Form2)Application.OpenForms[\"Form2\"];
在您的代码示例中,可能看起来像这样:
public void StartConnection(string name)
{
//var myForm = Form.ActiveForm as Form2;
var myForm = Application.OpenForms[\"Form2\"] as Form2;
myForm.textBox1.Text = \"Hello world!\"; /// <- this one trows “System.NullReferenceException was unhandled”
/// unless Form2 is selected when this fires.
callback.Message_Server2Client(\"Welcome,\" + name );
}
就是说,我不认为我有责任为WCF服务修改表单控件。我会更快地消耗表单中服务触发的事件。
,myForm
可能不是Form2
类型,或者可能不包含textBox1
字段。对于这两种情况,请确保检查是否为空。