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

时间:2018-03-30 21:49:55

标签: c#

我正在尝试创建一个支持以下内容的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方法。这是最简单的方法。但是,我意识到我想让它更简单&#34;使用。我意识到我不知道如何根据&#34;示例&#34;声明/编写此代码。以上。它甚至可能吗?

2 个答案:

答案 0 :(得分:5)

您可以为此类创建索引器:

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"

答案 1 :(得分:1)

对于前两个问题,您可以使用indexers。这些允许访问类,就像使用数组一样。

例如,这可能是一个实现:

class Test
{
    private string[,] cells;

    public Test(int height, int width)
    {
        cells = new string[height, width];
    }

    // This is where it gets interesting : this will be called when you access your class, for example, like this :
    // Test t = new Test(5, 5);
    // t[2, 3] = "test"; => set will be called
    // or 
    // Console.WriteLine(t[2, 3]); => get will be called
    public string this[int y, int x]
    {
        get
        {
             return cells[y, x];
        }
        set
        {
           cells[y, x] = value; // Value is the part which is after the "="
        }
    }
}

您可以轻松地根据您的具体需求调整代码。 但是,我认为没有办法用圆括号来表达这一点。

关于excel部分,我不知道如何在C#中操作excel文件,我强烈建议你制作另一个主题,因为有一个“一个问题=一个主题”的方法。

PS:关于你提出的评论“换句话说,使用数组,而不是列表”。这是在实现方面,它与您使用类的方式没有任何关系。