How can I simplify C# code that sets multiple properties of an object?

后端 未结 5 1239
没有蜡笔的小新
没有蜡笔的小新 2021-02-07 00:30

I have code that looks like this:

itemView.Question.AnswersJSON = itemView.Answer.ToJSONString();
itemView.Question.Modified = DateTime.Now;
itemView.Question.Mo         


        
5条回答
  •  一个人的身影
    2021-02-07 01:17

    If Question is a class (not a struct), then you could assign it to a local variable, and edit that:

    Question q = itemView.Question;
    q.AnswersJSON = itemView.Answer.ToJSONString();
    q.Modified = DateTime.Now;
    q.ModifiedBy = User.Identity.Name
    

    You won't even have to assign q back to itemView.Question.

    This is because classes in C# are reference types. If you assign an instance of a reference type to a local variable, or pass it to a function, then changes to that instance will be reflected everywhere you have a reference to that same instance.

    Edit

    Note that the situation might be a bit murky if Question is a property of itemView, rather than a field. Depending on how it is implemented, you might have to assign q back to Question. In such a case, this code is still much preferred to avoid calling the Question property's getter method repeatedly.

提交回复
热议问题