简体   繁体   English

将参数传递给C#中的函数

[英]Passing parameter to a function in C#

I have a small program. 我有一个小程序。 It includes a listbox and few textboxes. 它包括一个列表框和几个文本框。 There are few elements in the listbox and depending on the selected index it outputs the corresponding values into the textboxes. 列表框中的元素很少,并且根据所选索引,它会将相应的值输出到文本框中。

Code example: http://notepad.cc/share/AGh5zLNjfJ 代码示例: http : //notepad.cc/share/AGh5zLNjfJ

I want to use a function to print the values into the textboxes instead of typing them over and over again in switch cases. 我想使用一个函数将值打印到文本框中,而不是在切换情况下一遍又一遍地键入它们。

Something like this: 像这样:

switch(personList.SelectedIndex)
{
    case 0:
        output(person1);
        break;
    case 1;
        output(person2);
        break;
}

I couldn't pass the person object and access its properties with the function I created. 我无法通过创建的函数传递person对象并访问其属性。 SOS. SOS。

Instead of switching by selected index, assign list of persons as data source to listbox. 不用按选定的索引切换,而是将人员列表作为数据源分配给列表框。 When selected index changes - show data of selected item in textboxes: 当选定索引更改时-在文本框中显示选定项目的数据:

// that's just creating list of People with NBuilder
var people = Builder<Person>.CreateListOfSize(5).Build().ToList();
personList.DisplayMember = "fname"; // set name of property to be displayed
personList.DataSource = people;

Then on selecting person from list: 然后从列表中选择人:

private void personList_SelectedIndexChanged(object sender, EventArgs e)
{
    Person person = (Person)personList.SelectedItem;
    output(person);
}

Keep in mind that in C# we use PascalNaming for methods and properties. 请记住,在C#中,我们对方法和属性使用PascalNaming。

Is your output function similar to this ?? 您的输出功能与此类似吗?

public void output(Person p)
{
    idBox.Text = p.id;
    nameBox.Text = p.name;
    lNameBox.Text = p.lName;
}

You can get selected Item as following (if you have bounded the listbox with list of person as datasource) 您可以按以下方式获取选定的项(如果您已将人员列表作为数据源来限制列表框)

Person p = (Person)listBox1.SelectedItem;

From your code i guess you need a function. 从您的代码中,我想您需要一个功能。 you can do it like this 你可以这样

private void Output(Person p)
{
     idBox.Text = p.id;
     fnameBox.Text = p.name;
     lNameBox.Text = p.lName;
}

and call it like you are calling. 然后像打电话一样打电话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM