C#更新另一个班级

时间:2017-03-10 20:52:52

标签: c#

我真的坚持这个问题。我有两个班,人和费用。 Person具有属性MyName和List Expense作为成员。在Expense类中,它具有属性MyFoodCost。我有一个表格,允许我输入/更新MyFoodCost的费用。在表格中,我有名单人,因为会有更多的人。因此,如果我想更新特定人员的MyFoodCost费用,我该怎么做?这个特定的人是否会有MyFoodCost的新更新费用?

public class Expense
{
    private decimal MyFoodCost;

    public Expense(decimal food)
    {
        MyFoodCost = food;
    }

    public decimal FoodCost
    {
        set
        {
            MyFoodCost = value;
        }
        get
        {
            return MyFoodCost;
        }
    }
}

public class Person
{
    private string MyName;
    public List<Expense> MyExpense;

    public Person(string name, decimal food)
    {
        MyName = name;
        MyExpense = new List<Expense>();
        MyExpense.Add(new Expense(food));
    }

    public string FullName
    {
        set
        {
            this.MyName = value;
        }
        get
        {
            return this.MyName;
        }
    }
}

public partial class BudgetForm : Form
{
    public List<Person> person;

    public BudgetForm()
    {
        InitializeComponent();

        person = new List<Person>();
    }

    private void buttonAddExpense_Click(object sender, EventArgs e)
    {
        decimal food = 0;

        food = decimal.Parse(TextBoxFood.Text);

        string name = ComboBoxPerson.SelectedItem.ToString();
        if(person.Count == 0)
        {
            person.Add(new Person(name, food));
        }
        else
        {
            Person you = person.FirstOrDefault(x => x.FullName == name);
            if (you == null)
            {
                person.Add(new Person(name, food));
            }
            else
            {
                foreach (var item in person)
                {
                    //check if person exists?
                    if (item.PersonName == name)
                    {
                        //person exists so update the food cost for him only.
                        //should i code to update the food
                        //or do somewhere else?
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您已经找到了Person个对象。我想你只想将新费用添加到该人的费用清单中。像这样:

Person you = person.First(x => x.FullName == name);
if (you == null)
{
    person.Add(new Person(name, food));
}
else
{
    you.MyExpense.Add(new Expense(food));
}