我正在尝试创建一个支持以下内容的C#类...
// Sets a string: sg(1,1) = "value";
// Gets a string: "value" = sg(1,1);
// sg.ExportToExcel(ClosedXML.Excel.Worksheet, row = 1, col = 1) // Write sg to Excel for worksheet X, starting at row or row/col
Example Usage:
StringGrid sg = new StringGrid();
// Row/Col addressable "cells"
sg(1,1) = "Eastern Cities";
sg(2,1) = "Boston";
sg(3,1) = "New York";
sg(4,1) = "Atlanta";
// Skipping second 'column' is intentional and needs to be rendered correctly by ExportToExcel() [in other words, use Arrays, not List<string>]
sg(1,3) = "Western Cities";
sg(2,3) = "Los Angeles";
sg(3,3) = "Seattle";
Console.WriteLine(sg(2,1)); // Outputs "Boston"
sg.ExportToExcel(ws,row: 10);
Run Code Online (Sandbox Code Playgroud)
是的,它只是一个二维字符串网格,使用[string]数组和另一个方法[并且它从1,1开始,而不是0,0].
首先,我知道如何创建getValue/setValue方法.这是最简单的方法.但是,我意识到我想让它"更简单"使用.我意识到我不知道如何根据上面的"示例"声明/编写此代码.它甚至可能吗?
你可以为你的类创建索引器,如下所示:
class StringGrid {
// just a sample storage
// might actually work if you only need to address whole rows
// but not whole columns
private readonly Dictionary<int, Dictionary<int, string>> _values = new Dictionary<int, Dictionary<int, string>>();
// indexer
public string this[int x, int y]
{
get
{
// various checks omited
return _values[x][y];
}
set
{
if (!_values.ContainsKey(x))
_values.Add(x, new Dictionary<int, string>());
_values[x][y] = value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后将所有"("改为"["和")"更改为"]",它将起作用:
sg[1, 1] = "Eastern Cities";
sg[2, 1] = "Boston";
sg[3, 1] = "New York";
sg[4, 1] = "Atlanta";
// Skipping second 'column' is intentional and needs to be rendered correctly by ExportToExcel() [in other words, use Arrays, not List<string>]
sg[1, 3] = "Western Cities";
sg[2, 3] = "Los Angeles";
sg[3, 3] = "Seattle";
Console.WriteLine(sg[2, 1]); // Outputs "Boston"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |