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

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

    One option is that you can convert your properties into methods that return 'this'.

    Then you could write:

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

    I've heard this style called 'fluent interface', and find it pretty handy. I sometimes create properties and a matching set methods returning 'this' called SetXXXX to compliment them.

    The popular Rhino Mocks framework for unit testing uses it. More examples here: http://www.codeproject.com/Articles/99542/Guidelines-to-Fluent-Interface-design-in-C-Part-1

提交回复
热议问题