How can I assign multiple object properties at once in C#?

后端 未结 5 428
一个人的身影
一个人的身影 2021-01-20 15:08

Background

I have some rows from a DataGridView that I convert to entity objects. In the conversion process I reset some values. As the \"basic\" data

5条回答
  •  情深已故
    2021-01-20 15:50

    you can assign them in a chain using the = operator:

    TimeEntries.Hours = TimeEntries.Expenses = 0;
    

    as if you would read this statement backwards.

    In the case of your loop it would look like this:

    foreach (DataGridViewRow CurrRow in DataGridView.Rows)
    {
        SomeObject SomeObj = (SomeObject) CurrRow.DataBoundItem;
        SomeObj.PropertyA = SomeObj.PropertyB = 0;
        SomeObjCollection.Add(SomeObj);
    }
    

    Important note:

    If you are dealing with reference types this will assign only 1 reference to different properties. So that changing one of them will affect all other properties!

提交回复
热议问题