我目前正在C#上练习OOP。我似乎在从另一个表单中检索字符串时遇到问题。我有两种形式。发布者表单,我将字符串发送到其他表单,以及接收字符串的人员表单。请参考以下代码。
public partial class Publisher : Form
{
Subject s = new Subject();
Observer p, j;
Person paul, john;
public Publisher()
{
InitializeComponent();
}
private void Publisher_Load(object sender, EventArgs e)
{
paul = new Person(s, "Paul", new Observer(s, "Paul"));
paul.Show(); //opens a new form paul
john = new Person(s, "John", new Observer(s, "John"));
john.Show(); //opens a new form john
}
private void btnsend_Click_1(object sender, EventArgs e)
{
s.Message = textBox1.Text;
s.Notify();
}
}
这是个人表格。
public partial class Person : Form
{
string name;
Subject s;
Observer p;
Publisher ps = new Publisher();
public Person(Subject s, string name, Observer p)
{
InitializeComponent();
this.s = s;
this.name = name;
this.p = p;
}
private void Paul_Load(object sender, EventArgs e)
{
Text = name;
}
public void btnregister_Click(object sender, EventArgs e)
{
s.Attach(p);
s.Notify();
btnregister.Enabled = false;
btnunregister.Enabled = true;
}
public void btnunregister_Click(object sender, EventArgs e)
{
s.Detach(p);
s.Notify();
btnregister.Enabled = true;
btnunregister.Enabled = false;
}
}
此项目包括实现到接口的其他类。
public class Observer : IObserver
{
Subject subj;
string name;
Person p;
public Observer(Subject subj, string name) //Constructor
{
this.subj = subj;
this.name = name;
}
public void Update()
{
p.textBox1.Text = subj.Message; //I also get nullreference here
}
}
public interface IObserver
{
void Update();
}
这是另一个类:
public class Subject : ISubject
{
List<IObserver> observers = new List<IObserver>();
string message;
public string Message
{
get { return message; }
set { message = value; }
}
public void Attach(IObserver o)
{
observers.Add(o);
}
public void Detach(IObserver o)
{
observers.Remove(o);
}
public void Notify()
{
foreach (IObserver o in observers)
o.Update(); //I often get nullreference values from here
}
}
public interface ISubject
{
void Attach(IObserver o);
void Detach(IObserver o);
void Notify();
}
这是表格的输出。 Click here.
我相信已经调用了正确的类,并实例化了正确的对象。虽然,我似乎无法向其他表单发送字符串/消息。我做得对吗还是我在代码上缺少什么?
以下是一些指导目标:
任何帮助都将深表感谢。谢谢!