如何在C#中一次分配多个对象属性?
背景
我有一些来自DataGridView的行,我转换为实体对象.在转换过程中,我重置了一些值.由于“基本”数据来自当前DataGridViewRow的DataBoundItem,因此使用对象初始值设定项不是我正在寻找的选项,我不想再分配来自DataBoundItem的第一个对象的每个值(冗余) ). 所以我的问题是:是否可以一次分配多个对象属性,如果,你是如何实现它的? 研究 我发现了以下问题,但没有一个能解决我的问题: Assigning multiple variables at once in c# Assign multiple variables at once Setting multiple properties with one declaration in Windows Forms (C#) 码 foreach (DataGridViewRow CurrRow in DataGridView.Rows) { SomeObject SomeObj = (SomeObject) CurrRow.DataBoundItem; SomeObj.PropertyA = 0; SomeObj.PropertyB = 0; SomeObjCollection.Add(SomeObj); } 我试过了什么 单独使用逗号分配属性(在昏迷时给出语法错误): TimeEntries.Hours,TimeEntries.Expenses = 0; 解决方法
您可以使用=运算符在链中分配它们:
TimeEntries.Hours = TimeEntries.Expenses = 0; 好像你会向后看这个陈述. 对于你的循环,它看起来像这样: foreach (DataGridViewRow CurrRow in DataGridView.Rows) { SomeObject SomeObj = (SomeObject) CurrRow.DataBoundItem; SomeObj.PropertyA = SomeObj.PropertyB = 0; SomeObjCollection.Add(SomeObj); } 重要的提示: 如果您正在处理引用类型,则只会为不同的属性分配1个引用.因此,更改其中一个将影响所有其他属性! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |