gpt4 book ai didi

c# - 如何在对象上声明没有名称的 Get/Set 方法?

转载 作者:行者123 更新时间:2023-11-30 20:16:18 24 4
gpt4 key购买 nike

我正在尝试创建一个支持以下内容的 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);

是的,它只是一个二维字符串网格,使用 [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;
}
}
}

然后将所有的“(”改为“[”,“)”改为“]”即可:

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"

关于c# - 如何在对象上声明没有名称的 Get/Set 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581861/

24 4 0
文章推荐: c# - 从 List 枚举初始化 List