如何将类的实例传递给另一个表单c#

时间:2014-10-09 17:51:10

标签: c# forms class instance

因此,在主窗口类顶部的顶部,我声明了我的staff类的一个实例,称之为staff1

public partial class MainWindow : Window
{

    Staff staff1 = new Staff();
    public double grossPay;
    public double taxRate;
    public MainWindow()
    {           
        InitializeComponent();
    }

    private void btnSet_Click(object sender, RoutedEventArgs e)
    {
        staff1.staffID = Convert.ToInt32(txtStaffID.Text);
        staff1.firstName = txtFirstName.Text;
        staff1.surname = txtSurname.Text;
        staff1.dob = txtDOB.Text;
        staff1.department = txtDepartment.Text;
        staff1.hourlyPayRate = Convert.ToDouble(txtPayRate.Text);
        staff1.hoursWorked = Convert.ToDouble(txtHoursWorked.Text);
   }

    private void btnClear_Click(object sender, RoutedEventArgs e)
    {
        txtStaffID.Text = "";
        txtFirstName.Text = "";
        txtSurname.Text = "";
        txtDOB.Text = "";
        txtDepartment.Text = "";
        txtPayRate.Text = "";
        txtHoursWorked.Text = "";
    }

    private void txtDOB_TextChanged(object sender, TextChangedEventArgs e) { }

    private void btnGet_Click(object sender, RoutedEventArgs e)
    {
        txtStaffID.Text = Convert.ToString(staff1.staffID);
        txtFirstName.Text = staff1.firstName;
        txtSurname.Text = staff1.surname;
        txtDOB.Text = staff1.dob;
        txtDepartment.Text = staff1.department;
        txtPayRate.Text = Convert.ToString(staff1.hourlyPayRate);
        txtHoursWorked.Text = Convert.ToString(staff1.hoursWorked);
    }

    private void btnCalcPay_Click(object sender, RoutedEventArgs e)
    {
        grossPay = staff1.calcPay();
        taxRate = staff1.calcTaxRate();
        Payslip P = new Payslip();
        P.Show();     
    }
}

}

然后我有另一个名为Payslip的表单,我想要做的就是能够以新的形式访问我的类的staff1实例,但我不能

public partial class Payslip : Window
{
    public Payslip()
    {
        InitializeComponent();
       // Want to be able to access staff1 here ????
    }
}

}

2 个答案:

答案 0 :(得分:1)

只需通过构造函数

传递它
// make a constructor in the second form that takes Staff as parameter
Staff _staff;
public Payslip(Staff s)
{
   InitializeComponent();
   _staff = s;
}

private void btnCalcPay_Click(object sender, RoutedEventArgs e)
{
    grossPay = staff1.calcPay();
    taxRate = staff1.calcTaxRate();
    // pass the staff1 instance to constructor when creating the Form 
    Payslip P = new Payslip(staff1); 
    P.Show();
}

答案 1 :(得分:0)

您可以将Staff作为参数传递给构造函数。

public partial class Payslip : Window
{
    Staff staff_;
    public Payslip()
    {
        InitializeComponent();
        //Want to be able to access staff1 here ????
    }

    public Payslip(Staff staff)
    {
        InitializeComponent();
        //Want to be able to access staff1 here ????
        staff_ = staff;
    }

}