带有 excel 的 IEnumerable yield return 函数

IEnumerable yield return function with excel

我从C#开始,在使用Interop也是如此

我的目标 是创建一个 windows 应用程序,它可以 return Excel 的值。

我的问题 是在进行循环时,我最终只得到第一个值,因为 "return" 关闭了循环。

我做了什么 为了尝试解决这个问题,我在我的函数上使用了 "IEnumerable",同时保持类型 "string".

return 函数 SDExpFormsApp1.Excel+d__6

我不明白为什么 return 是 class 后面跟着 "d__6"

的名称

我试图在这里找到一些有趣的东西: https://docs.microsoft.com/fr-fr/dotnet/api/system.collections.generic.ienumerator-1?view=netcore-3.1

我的活动功能

private void button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        string filename = openFileDialog1.FileName;
        int sheet = int.Parse(textBox1.Text);
        Excel excel = new Excel(filename, sheet);
        string SuperClass = excel.ReadCell(1, 1);
        string ClassName = excel.ReadCell(2, 1);
        string ClassLabel = excel.ReadCell(3, 1);
        string AttrName = excel.ReadCell2(8, 1).ToString();
        richTextBox1.Text =  "" + AttrName;

    }

我的函数读取excel

public IEnumerable<string> ReadCell2(int i, int j)
    {
        try
        {

            while (ws.Cells[i, j].Value2 != null)
            {
                Console.WriteLine(ws.Cells[i, j].Value2);
                yield return ws.Cells[i, j].Value2;
                i++;
            }
        }
        finally
        {

        }
        yield return "nothing";
    }

ToString默认不会为collection/enumerables和returns类型名重载,不会枚举底层IEnumerable,所以需要使用string.Join:

string AttrName = string.Join("", excel.ReadCell2(8, 1));

至于为什么在这种特殊情况下 ToString returns SDExpFormsApp1.Excel+d__6 - 这是因为 yield return 实际上是一个语法糖,编译器会生成 IEnumerable<T>为您实现,它将包含类型名称作为其自身的一部分。例如,您可以在 this 问题的答案中阅读更多相关信息。