最近开始学习C#编程:静态字段和静态方法的学习,windows Form 设计如图1,输入原库存量,单价,销售数量,计算出,现库存量和销售额
图 1
代码实现如下,Form1和Form2功能相同,只不过在,一个类中调用另一个类的静态字段数据时,
1)通过静态方法返回需要的字段数据,需要建立返回静态方法
2)通过类名直接应用静态字段数据(前提是字段是public的),不需要建返回静态字段方法
通过静态方法返回需要的字段数据:
namespace crashRegister
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int st;
int inYanKuCun = Convert.ToInt32(textBox1.Text.Trim());
int inCost = Convert.ToInt32(textBox2.Text.Trim());
int inXianKuCun = Convert.ToInt32(textBox3.Text.Trim());
Among a= new Among(inYanKuCun,inCost);
a.MakeIt(inXianKuCun,out st);
textBox4.Text = st.ToString();
textBox5.Text = Among.ChuanZhi().ToString();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = textBox5.Text = "";
}
}
public class Among
{
int numYanKuCun;
int numCost;
static double xiaoShouE;
public Among(int m,int n)
{
this.numYanKuCun = m;
this.numCost=n;
}
static Among()
{
xiaoShouE=0.0;
}
public void MakeIt(int num,out int stock)
{
numYanKuCun -= num;
xiaoShouE=numCost*numYanKuCun;
stock=numYanKuCun;
}
static public double ChuanZhi()
{
return xiaoShouE;
}
}
}
通过类名访问静态字段的数据:
1 namespace crashRegister
2 {
3 public partial class Form1 : Form
4 {
5 public Form1()
6 {
7 InitializeComponent();
8 }
9 private void button1_Click(object sender, EventArgs e)
10 {
11 int st;
12 int inYanKuCun = Convert.ToInt32(textBox1.Text.Trim()); //在textBox1中输入原库存数量赋值给inYanKuCun.
13 int inCost = Convert.ToInt32(textBox2.Text.Trim()); //在textBox2中输入单价给inCost;
14 int inXianKuCun = Convert.ToInt32(textBox3.Text.Trim()); //在textBox3中输入销售数量给inXianKuCun.
15 Among a= new Among(inYanKuCun,inCost);
16 a.MakeIt(inXianKuCun,out st);
17 textBox4.Text = st.ToString();
18 textBox5.Text = Among.xiaoShouE.ToString();
19
20
21 }
22
23 private void button2_Click(object sender, EventArgs e)
24 {
25 textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = textBox5.Text = "";
26 }
27 }
28 public class Among
29 {
30 int numYanKuCun;
31 int numCost;
32 public static double xiaoShouE;
33 public Among(int m,int n)
34 {
35 this.numYanKuCun = m;
36 this.numCost=n;
37 }
38
39 public void MakeIt(int num,out int stock)
40 {
41 numYanKuCun -= num;
42 xiaoShouE=numCost*numYanKuCun;
43 stock=numYanKuCun;
44
45 }
46
47 }
48 }