gpt4 book ai didi

c# - 如何将一个类的实例传递给另一个窗体 C#

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:52 25 4
gpt4 key购买 nike

因此,在主窗口类的顶部,我声明了一个员工类的实例,并将其命名为 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 的表单,我想做的就是能够以新表单访问我类(class)的 staff1 实例,但我不能

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

最佳答案

通过构造函数传递给它

// 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();
}

关于c# - 如何将一个类的实例传递给另一个窗体 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26284865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com