【问题标题】:Can I use same Class Format list in a Custom Class List?我可以在自定义班级列表中使用相同的班级格式列表吗?
【发布时间】:2021-04-28 22:10:48
【问题描述】:

我正在尝试在 DataGridView 中添加撤消功能

我实现了逐个处理单元格的功能,但还没有实现撤消大单元格的功能。

public class UndoBuffer
{
    public string undoCell { get; set; }
    public int rowIndex { get; set; }
    public int colIndex { get; set; }
}

这是有问题的代码。

第一次执行时,声明类类型的列表,在单元格编辑开始和结束时,依次保存上一个值、行、列。

但是,执行删除、粘贴或替换等操作后,代码无法正常工作。

所以我尝试在类中添加一个列表,以便在处理大单元格时使用。

这样

 public class UndoBuffer
{
    public string undoCell { get; set; }
    public int rowIndex { get; set; }
    public int colIndex { get; set; }

    public List<UndoBuffer> bufferArray = new List<UndoBuffer>();  //Added Code
}

声明它没有问题,但是当我尝试使用它时,我遇到了语法错误。

这段代码是我在给缓冲区栈一个一个分配的时候写的

 private List<UndoBuffer> undoBuffers = new List<UndoBuffer>(); //Declare CustomList
 ...
 ...
 undoBuffers.Add(new UndoBuffer() { undoCell = beginEditCell, rowIndex = e.RowIndex, colIndex = e.ColumnIndex }); 

并且这段代码被用来在缓冲区堆栈上分配大量单元格。

List<UndoBuffer> undobuffer = new List<UndoBuffer>();

List<UndoBuffer> array = new List<UndoBuffer>();
array.Add(new UndoBuffer()
{
     undoCell = "BeginCell",
     rowIndex = 33,
     colIndex = 2
});
array.Add(new UndoBuffer()
{
     undoCell = "BeginCell",
     rowIndex = 34,
     colIndex = 3
});

**undobuffer.Add(new UndoBuffer() {bufferArray.AddRange(array) });** // Grammar error code

我的编码方向是否错误,而不仅仅是语法错误?

请,任何建议将不胜感激。

谢谢你

【问题讨论】:

  • new UndoBuffer() {bufferArray = array }?
  • 谢谢,修复类代码后( public List bufferArray = { get; set;} ),我执行了代码,它工作正常。

标签: c# datagridview undo


【解决方案1】:

在创建类型对象的新实例时,在初始化成员时,我们不能将指令作为完整语句执行。我们只能做赋值,即使是调用方法或 lambda,所以 function 有一个返回结果。这里只是过程调用,所以什么都不返回。

因此,为了不替换整个列表,并且能够添加范围,我们需要将事物解耦并编写:

var buffer = new UndoBuffer();
buffer.bufferArray.AddRange(array);
undobuffer.Add(buffer);

另外,bufferArray 似乎是 composite,因此它应该是一个 get only 属性(如果是公共的),或者是一个 只读私有或受保护的字段,已初始化在声明时,或在构造函数中:

public List<UndoBuffer> bufferArray { get; } = new List<UndoBuffer>();

我建议您改进命名,使其更加标准、相关和简洁,例如:

public class UndoBuffer
{
    public string UndoCellText { get; set; }
    public int RowIndex { get; set; }
    public int ColIndex { get; set; }

    public List<UndoBuffer> Buffers { get; } = new List<UndoBuffer>();
}

C# Coding Conventions (C# Programming Guide)

C# Naming Conventions

C# Coding Standards and Naming Conventions

【讨论】:

  • 非常有帮助.. 谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多