[英]C# Creating a list of a custom class. Values are not saving properly
我有一个自定义类“ Actions”,它正在加载2个属性:一个范围和一个名为“ Action”的字符串。 我正在使用range.find遍历一个excel文档来尝试存储范围列表。 但是,(并且我看到这只是设计使然。),每次我找到新范围时更改“ currentAct”属性的值时,它将为列表中所有对象设置属性之前已添加。 如何解决这个问题,使列表具有所有不同的值?
Excel.Workbook activeWorkBook = Globals.ThisAddIn.Application.ActiveWorkbook;
Excel.Worksheet activeWorkSheet = activeWorkBook.ActiveSheet;
Excel.Range colRange = activeWorkSheet.Columns["A:A"];
Excel.Range resultActionFirstRange = null;
Excel.Range resultActionCurrentRange = null;
/*This is my custom list: ActionRangeList*/
List<Actions> ActionRangeList = new List<Actions>();
/* This is what I'm using to set the properties of the class before adding to the list */
Actions currentAct = new Actions();
string actionValue;
string DBName;
string TblName;
int actionCol;
int actionRow;
string searchActionLabel = "Action=>";
string searchDBLabel = "DatabaseName=>";
string searchTblLabel = "TableName=>";
resultActionCurrentRange = colRange.Find(searchActionLabel, Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing);
//get action
while (resultActionCurrentRange != null)
{
if (resultActionFirstRange == null)
{
resultActionFirstRange = resultActionCurrentRange;
actionCol = resultActionFirstRange.Column + 1;
actionRow = resultActionFirstRange.Row;
actionValue = (string)(activeWorkSheet.Cells[actionRow, actionCol] as Excel.Range).Value;
currentAct.Action = actionValue;
currentAct.actionRange = (Excel.Range)(activeWorkSheet.Cells[actionRow, actionCol]);
ActionRangeList.Add(currentAct);
}
else if (resultActionCurrentRange.get_Address(Excel.XlReferenceStyle.xlA1) == resultActionFirstRange.get_Address(Excel.XlReferenceStyle.xlA1))
{
break;
}
//search for next range
resultActionCurrentRange = colRange.FindNext(resultActionCurrentRange);
//check if we looped back to the beginning yet
if (resultActionCurrentRange.get_Address(Excel.XlReferenceStyle.xlA1) != resultActionFirstRange.get_Address(Excel.XlReferenceStyle.xlA1))
{
actionCol = resultActionCurrentRange.Column + 1;
actionRow = resultActionCurrentRange.Row;
actionValue = (string)(activeWorkSheet.Cells[actionRow, actionCol] as Excel.Range).Value;
currentAct.Action = actionValue;
currentAct.actionRange = (Excel.Range)(activeWorkSheet.Cells[actionRow, actionCol]);
ActionRangeList.Add(currentAct);
}
}
private class Actions
{
public Excel.Range actionRange { get; set; }
public string Action { get; set; }
}
正如Anthony Pegram所说的,我只需要在每次循环迭代中创建一个新实例。 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.