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

后端 未结 5 430
一个人的身影
一个人的身影 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:40

    This answer is intended as a canonical to show both ways of setting the values.

    The first option as explained in the answer by Mong Zhu is to simply chain the = operator:

    int a, b;
    a = b = 0;
    

    But the crux in this is the fact that if you are working with reference types, only one reference will be assigned. In that case, the answer from Dennis_E, which uses tuple deconstruction, would work:

    int a, b;
    (a, b) = (0, 0);
    

    Important note: To run the latter code you either need to be compiling on .NET 4.7 or higher. If you are running .NET 4.6.2 or lower, install the NuGet package System.ValueTuple by running this command in your package manager console:

    Install-Package "System.ValueTuple"
    

提交回复
热议问题