passing parameters via function
I'm making a C# airlines reservation project, taking the user details via form1, say I have a class Passen开发者_StackOverflowgerDetails
with class variables. Now, on click of the button, I need to assign all those TextBox
values to the class variables
private void btnSubmit_Click(object sender, EventArgs e)
{
string fn = txtFname.Text;
string ln = txtLname.Text;
string add = txtAddress.Text;
int age = int.Parse(txtAge.Text);
submit(fn, ln, add, age);
}
I need to pass these to the function. How should I declare it?
Create a class for passenger data and pass this as a parameter.
class Passenger
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}
private void AddButton_Click(object sender, EventArgs e)
{
var passenger = new Passenger
{
FirstName = txtFname.Text,
LastName = txtLname.Text,
Address = txtAdd.Text,
Age = int.Parse(txtAge.Text)
};
AddPassenger(passenger);
}
Can't you just make a simple assignment?
public class MyClass
{
public string fn;
public string ln;
public string add;
public int age;
}
the submit function is
submit(string fn, string ln, string add, int age)
{
MyClass myclass = new MyClass();
myclass.fn = fn;
myclass.ln = ln;
myclass.add=add;
mycalss.age = age;
}
You would have a form-level variable that stores an instance of your passenger details class can call that:
Note: pseudo code! Do not copy and paste!
class form1()
{
private passenger_details = new PassengerDetail()
private void button_click()
{
passenger_details.age = int(nameField.Text);
}
}
You could also overload your constructor:
class Passenger
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int Age { get; set; }
void Passenger() {}
void Passenger(string _firstName, string _lastName, string _address, int _age)
{
this.FirstName = _firstName;
this.LastName = _lastName;
this.Address = _address;
this.Age = _age;
}
}
Then your event would just assign them at creation. (following code assumes you have a global variable called MyPassenger)
private void btnSubmit_Click(object sender, EventArgs e)
{
this.MyPassenger = new Passenger(txtFname.Text, txtLname.Text, txtAddress.Text, int.Parse(txtAge.Text));
}
精彩评论