我有三个类,代码如下。
网络 - 添加和删除电话,处理呼叫 当添加到网络时,Phone1和Phone2可以互相呼叫。
但是当我将两部手机连接到网络并尝试将phone1拨打到phone2时,我遇到了问题,它一直在给我"接收器忙碌"。我试图在从phone1调用时进行一些调试并读取phone2的状态,但它返回一个空字符串(实际应该返回" A",当它被添加到网络中时)。
任何帮助都会非常感激。
-----网络类------------------
namespace Demo
{
public partial class network : Form
{
phone1 p1 = new phone1();
phone2 p2 = new phone2();
public network()
{
InitializeComponent();
}
public Boolean numberValidator(int number)
{
Boolean exist = false;
if (comboBox2.Items.Equals(number))
{
exist = true;
}
return exist;
}
public void processCall(int rNumber)
{
if (!numberValidator(rNumber))
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Not connected";
//MessageBox.Show(p2.returnPhoenStatus());
}
else
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call in progress";
p2.receiveCall(1);
p1.setStatus("Busy");
/*
if (p2.btnCallPressStatus())
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call initiated";
}*/
}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
{
p1.Show();
comboBox2.Items.Add(1);
p1.setStatus("A");
}
if (comboBox1.SelectedIndex == 1)
{
p2.Show();
comboBox2.Items.Add(2);
p2.setStatus("A");
}
}
}
}
---------- Phone1 Class ---------
namespace Demo
{
public partial class phone1 : Form
{
public phone1()
{
InitializeComponent();
}
string status;
public void setStatus(string Status)
{
status = Status;
}
public string returnStatus()
{
return status;
}
public void receiveCall(int callerNumber)
{
setStatus("Busy");
btnCall.Text = "Answer";
textBox1.Text = "Phone " + callerNumber + " Calling.";
}
public void makeCall(int number)
{
phone2 p2 = new phone2();
network net = new network();
MessageBox.Show(p2.returnStatus()); // this line not returing status of phone2
if (p2.returnStatus() == "A")
{
net.processCall(number);
}
else
{
textBox1.Text = "Receiver Busy";
}
}
public TextBox TextBox1
{
get
{
return textBox1;
}
}
private void btnCall_Click(object sender, EventArgs e)
{
string number = textBox1.Text;
int numberInt = Convert.ToInt16(number);
makeCall(numberInt);
}
string phoneNo = "";
private void btn2_Click(object sender, EventArgs e)
{
phoneNo = phoneNo + btn2.Text;
textBox1.Text = phoneNo;
}
}
}
------------- phone2 Class --------------
namespace Demo
{
public partial class phone2 : phone1
{
public phone2()
{
InitializeComponent();
}
}
}
答案 0 :(得分:2)
我认为你正在设置P1的状态。检查网络类中button1_Click方法中的if条件。 setStatus应该是P2。
if (comboBox1.SelectedIndex == 1)
{
p2.Show();
comboBox2.Items.Add(2);
p2.setStatus("A");
}
答案 1 :(得分:0)
Piyush有正确的答案,但我想我会添加这个答案作为避免这种错误的方便提示。
尝试编写button1_Click
方法,如下所示:
private void button1_Click(object sender, EventArgs e)
{
var i = comboBox1.SelectedIndex;
var p = (new [] { p1, p2 })[i]; // Or `var p = i == 0 ? p1 : p2;`
p.Show();
comboBox2.Items.Add(i + 1);
p.setStatus("A");
}
这样可以避免代码重复和发生的错误输入。