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

后端 未结 5 1186
没有蜡笔的小新
没有蜡笔的小新 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 00:57

    Depending on how much control you have over the Question class, separating the resposibility for setting that meta-data may be an idea:

    class Question {
        ...
        public void SetAnswer(Answer answer) {
            this.AnswersJSON = answer.ToJSONString();
            this.Modified = DateTime.Now;
            this.Modified = User.Identity.Name; // or pass the user into SetAnswer()
        }
    }
    
    // in your UI code:
    itemView.Question.SetAnswer(itemView.Answer);
    

提交回复
热议问题