![](/img/trans.png)
[英]How can i print the returned value of a method into the method of the same class
[英]How to return a value in a method which is the same value returned in a try?
我實際上是在 C# 中編程,我有一個問題,我不知道該方法是否返回了我想要的。 事實上,我正在使用 try/catch 函數,我在其中返回一個值 (cellValue1),在我的方法結束時,我正在返回“”“;”。
該方法最后返回什么? 我想返回與 try 函數中相同的值嗎?
這是我的代碼:
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace excel
{
class Class1
{
public static void ReadExcel()
{
Var log = ConstLog.AreaLog.item1;
log+= "\n"
log+= "[REGION]-[read excel] : method read excel started" +"\n";
foreach (var files in Directory.GetFiles(@"C:\Users\Lionel84100\Desktop\Excel"))
{
string filepath = @"C:\Users\Lionel84100\Desktop\Excel\fezfFzfe.xlsx";
try
{
IWorkbook workbook = null;
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
if (filepath.IndexOf(".xlsx") > 0)
{
workbook = new XSSFWorkbook(fs);
}
else if (filepath.IndexOf(".xls") > 0)
{
workbook = new HSSFWorkbook(fs);
}
ISheet sheet = workbook.GetSheet("Formatage_IM");
if (sheet != null)
{
int rowCount = sheet.LastRowNum;
for (int i = 1; i <= rowCount; i++)
{
IRow curRow = sheet.GetRow(i);
string cellValue1 = curRow.GetCell(1).StringCellValue;
return cellValue1;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
return log;
}
我已經用 void 替換了方法開頭的字符串,但是有一個錯誤說我不能返回值,因為方法在 void 中。
該方法返回excel文件中第一個單元格的值,如果文件存在,則返回空字符串
不返回void
的方法必須始終返回一個值,除非它返回異常。
public string Foo(int i)
{
if (i == 0)
{
return "Zero";
}
// If you remove/comment the following line, the function will not compile.
return "Not Zero";
}
當 function 中有 try/catch 處理程序時,同樣適用:
public string Foo(int i)
{
try
{
if (i == 0)
{
return "Zero";
}
// If you remove/comment the following line, the function will not compile.
return "Not Zero";
}
catch (Exception)
{
// If you remove the following line, the function will also not compile,
// because if you handle an exception in a function, it needs to return a value as well (or rethrow the exception)
return "Error";
}
}
另一方面(如您的示例中),返回void
的 function不得返回值。 這意味着要么在return
語句之后必須沒有參數,要么根本沒有 return 語句。
因此,對於您的 function,您需要將返回類型從void
更改為string
,並確保在其他情況下也返回一個值(或者如果找不到值/單元格,則拋出異常)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.