繁体   English   中英

IEnumerable 收益率返回 function 和 excel

[英]IEnumerable yield return function with excel

我从C#开始,以及在使用Interop。

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

我的问题是,在制作循环时,我只得到了第一个值,因为“返回”关闭了循环。

我做了什么为了尝试解决这个问题,我在 function 上使用了“IEnumerable”,同时保留了“字符串”类型。

function SDExpFormsApp1.Excel+d__6 的返回

我不明白为什么返回的是 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;

    }

我的 function 读取 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通常不会为集合/枚举重载并默认返回类型名称,并且不会枚举底层IEnumerable ,因此您需要使用string.Join

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM