本文介绍了如何简化设置对象多个属性的C#代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下代码:

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

外加更多行设置 itemView 中的 Question 类的值。

plus many more lines where I set values for the Question class that is inside the itemView.

我认为答案是不可能的,只是将其作为问题提出,以防万一有人知道。

I think the answer is "not possible" but just putting it out as a question in case anyone knows a way.

我想做的是找到一种方法来简化此代码,而不必在每个代码中重复 itemView.Question

What I would like to do is to find a way to simplify this code without repeating itemView.Question in every line.

推荐答案

如果问题 class (不是 struct ),则可以将其分配给局部变量,然后进行以下编辑:

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

您甚至不必分配 q 返回 itemView.Question

这是因为C#中的类是。如果您将引用类型的实例分配给局部变量,或将其传递给函数,则对该实例的更改将在您引用该实例的任何地方得到反映。

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.

编辑

请注意,如果问题是 itemView 的属性,而不是字段。根据实现方式的不同,您可能必须将 q 分配给问题。在这种情况下,仍首选使用此代码,以避免重复调用 Question 属性的getter方法。

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.

这篇关于如何简化设置对象多个属性的C#代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 02:57