[英]Method not returning string value c# <List>
public List<string> Test_IsDataLoaded()
{
try
{
if (GRIDTest.Rows.Count != 0)
{
int countvalue = GRIDTest.Rows.Count;
GRIDTest.Rows[0].WaitForControlReady();
List<string> ReleaseIDList = new List<string>();
int nCellCount = GRIDTest.Cells.Count;
for(int nCount = 0;nCount<nCellCount ;nCount++)
{
if(nCount %5==0)
ReleaseIDList.Add((GRIDTest.Cells[0].GetProperty("Value").ToString()));
}
return ReleaseIDList;
}
}
catch (Exception)
{
}
}
方法抛出错误=并非所有代码路径都返回一个值。 代码有什么不对。
你的错误是:
并非所有代码路径都返回一个值
哪个是对的。 您只在if
语句中返回一个值:
if (GRIDTest.Rows.Count != 0)
如果GRIDTest.Rows.Count==0
怎么GRIDTest.Rows.Count==0
? 然后你不会返回一个值。
作为故障保护(如果您的代码错误,或者您的if语句不正确),您可以将以下内容添加到方法的最后一行:
return new List<string>();
这将确保如果没有其他返回,则将返回空List
您可以在方法的最后添加return
public List<string> Test_IsDataLoaded()
{
try
{
if (GRIDTest.Rows.Count != 0)
{
int countvalue = GRIDTest.Rows.Count;
GRIDTest.Rows[0].WaitForControlReady();
List<string> ReleaseIDList = new List<string>();
int nCellCount = GRIDTest.Cells.Count;
for(int nCount = 0;nCount<nCellCount ;nCount++)
{
if(nCount %5==0)
ReleaseIDList.Add((GRIDTest.Cells[0].GetProperty("Value").ToString()));
}
return ReleaseIDList;
}
}
catch (Exception)
{
}
return new List<string>() ;//<-------here
}
编译器抱怨,因为如果发生异常或if语句返回false,则不会执行return语句。
在方法的末尾添加默认的return语句。
抱怨上述问题背后的原因是你没有从整个方法返回值....它只从if condition
返回但是如果它跳过if statement
,那么就没有返回值。所以你必须是确定在整个方法中返回值....
你可以这样做:
public List<string> Test_IsDataLoaded()
{
List<string> ReleaseIDList = new List<string>();
try
{
if (GRIDTest.Rows.Count != 0)
{
int countvalue = GRIDTest.Rows.Count;
GRIDTest.Rows[0].WaitForControlReady();
int nCellCount = GRIDTest.Cells.Count;
for(int nCount = 0;nCount<nCellCount ;nCount++)
{
if(nCount %5==0)
ReleaseIDList.Add((GRIDTest.Cells[0].GetProperty("Value").ToString()));
}
}
}
catch (Exception)
{
}
return ReleaseIDList;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.