从方法正确返回字符串

本文关键字:返回 字符串 方法 | 更新日期: 2023-09-27 18:20:43

我有这个方法,我想返回一个字符串,我将在另一个方法中使用,但当我将return语句放在for循环中时,该方法仍然要求返回。如何正确地构造它,以便返回我想要的字符串。

public string ReadDocument(string fileName)
        {
            try
            {
                theImage = codecs.Load(Enhance(fileName), 0, CodecsLoadByteOrder.BgrOrGray, 1, -1); 
                for (int num = 1; num <= theImage.PageCount; num++)
                {
                    BarcodeData dataArray = engine.Reader.ReadBarcode(theImage, LogicalRectangle.Empty, 0, null);
 qrCode = dataArray.Value;
                    if (theImage.Page < theImage.PageCount)
                        theImage.Page++;       
                    return dataArray.Value;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

从方法正确返回字符串

为了编译此代码,您应该考虑在出现异常和for循环从未运行的情况下需要返回的值(是的,如果theImage.PageCount在运行时返回的值严格低于1,则可能会发生这种情况)。例如,您可以返回null:

public string ReadDocument(string fileName)
{
    try
    {
        theImage = codecs.Load(Enhance(fileName), 0, CodecsLoadByteOrder.BgrOrGray, 1, -1); 
        for (int num = 1; num <= theImage.PageCount; num++)
        {
            BarcodeData dataArray = engine.Reader.ReadBarcode(theImage, LogicalRectangle.Empty, 0, null);
            qrCode = dataArray.Value;
            if (theImage.Page < theImage.PageCount)
            {
                theImage.Page++;
            }
            return dataArray.Value;
        }
        return null;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
        return null;
    }
}

您可能会得到类似的错误,并非所有代码路径都返回值,因为您没有从catch语句返回任何内容。

您可以将dataArray.Value的值保存在字符串中,然后在catch语句之外(最后)返回该值。

public string ReadDocument(string fileName)
{
    string value = string.Empty;
    try
    {
        theImage = codecs.Load(Enhance(fileName), 0, CodecsLoadByteOrder.BgrOrGray, 1, -1);
        for (int num = 1; num <= theImage.PageCount; num++)
        {
            BarcodeData dataArray = engine.Reader.ReadBarcode(theImage, LogicalRectangle.Empty, 0, null);
            qrCode = dataArray.Value;
            if (theImage.Page < theImage.PageCount)
                theImage.Page++;
            value = dataArray.Value;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    return value;
}

更新:如果您想返回列表,那么只需将返回类型更改为List<string>,然后将项目添加到字符串中,并像这样返回

List<string> myValues=new List<string>();
for (int num = 1; num <= theImage.PageCount; num++)
        {
            BarcodeData dataArray = engine.Reader.ReadBarcode(theImage, LogicalRectangle.Empty, 0, null);
            qrCode = dataArray.Value;
        if (theImage.Page < theImage.PageCount)
            theImage.Page++;
        myValues.Add(dataArray.Value);
    }

然后返回myValues

您可能无法在此处返回正确的字符串,因为该方法的后置条件失败。你让它阅读一份文件,但它没有。你有三个有意义的潜在选择:

  1. 返回null。然后,您必须在调用者中处理一个null
  2. 如果您不能处理异常,请不要捕获它——让调用者来处理它
  3. 捕获异常,但重新抛出它,将其封装在其他类型中,以反映方法的失败后处理条件

如果您不从捕获中重新抛出,编译器会期望您返回一些东西——因此为null。

当您在这里读取单个条形码时,我建议使用IEnumerable<string>yield return运算符,而不是立即实际连接字符串。

以下是我的意思;我在这里有一些示例"页面",它们当然是你程序中的实际数据,但它给了我们一些可以使用的东西:

    // Example "pages", which would be individual barcodes read using OP's BarcodeReader, but we need some sample data to demonstrate the purpose.
    private string[] _pages = new string[] { "Mung", "Foo", "Bar", "Cookie" };

然后你可以在某个地方写下你的ReadDocument方法,如下所示:

    public IEnumerable<string> ReadDocument()
    {
        // Iterate over the pages, and use yield return to add every individual page to the IEnumerable.
        // Using the current Page and the PageLength in your for loop removes the need of having to manually check
        // whether we've reached the end of the pages further down the loop.
        for (int i = 0; i < _pages.Length; i++)
        {
            // BarcodeData dataArray = engine.Reader.ReadBarcode(theImage, LogicalRectangle.Empty, 0, null);
            // qrCode = dataArray.Value;
            yield return _pages[i]; // dataArray.Value in your own code.
        }
    }

这会给你一个很好的IEnumerable中你刚刚读过的所有页面,你可以稍后foreach来获得单独的页面,或者你可以通过沿着的线做一些事情来获得所有页面的字符串

ReadDocument().Aggregate(string.Empty, (current, s) => current + s);

与直接将所有读取的页面合并为字符串相比,这种方法的好处是,您仍然可以访问原始形式的所有数据,并且您可以自由地对其进行操作,而不需要在之后对其进行Split()

代码不再是你自己的代码,但它应该让你清楚地知道我建议你如何处理这个特定的问题;您应该能够调整它并在自己的代码中使用它,而不会出现太多问题。