我想将一个数组返回到WP 8页面并出现错误:not all code paths return a value
。我该如何纠正?
我的WCF服务具有以下代码:
public Point getAllusrs (int myID)
{
DataClasses1DataContext data = new DataClasses1DataContext();
var a = (from s in data.Tabs where s.u1ID == myID && s.status == true select s.u2ID).ToArray();
int inc = 0;
foreach (var d in data.Users)
{
if (a[inc] != null && d.Id == a[inc])
{
inc++;
return new Point() { Lat = d.usrLat, Lon = d.usrLong };
}
else inc++;
}
}
答案 0 :(得分:2)
当没有目标为Id
的用户时,您必须处理此案例。
例如,您可以在方法的末尾返回默认值:
public Point getAllusrs (int myID)
{
DataClasses1DataContext data = new DataClasses1DataContext();
var a = (from s in data.Tabs where s.u1ID == myID && s.status == true select s.u2ID).ToArray();
int inc = 0;
foreach (var d in data.Users)
{
if (a[inc] != null && d.Id == a[inc])
{
inc++;
return new Point() { Lat = d.usrLat, Lon = d.usrLong };
}
else inc++;
}
return default(Point); // or some Point with default Lat and Lon
}
或抛出一些例外:
public Point getAllusrs (int myID)
{
DataClasses1DataContext data = new DataClasses1DataContext();
var a = (from s in data.Tabs where s.u1ID == myID && s.status == true select s.u2ID).ToArray();
int inc = 0;
foreach (var d in data.Users)
{
if (a[inc] != null && d.Id == a[inc])
{
inc++;
return new Point() { Lat = d.usrLat, Lon = d.usrLong };
}
else inc++;
}
throw new Exception("Point not found"); // or some custom Exception
}
答案 1 :(得分:0)
这是因为如果代码不满足条件,它就不会返回任何值。
public Point getAllusrs (int myID)
{
Point pnt = null; // or new Point ();
DataClasses1DataContext data = new DataClasses1DataContext();
var a = (from s in data.Tabs where s.u1ID == myID && s.status == true select s.u2ID).ToArray();
int inc = 0;
foreach (var d in data.Users)
{
if (a[inc] != null && d.Id == a[inc])
{
inc++;
pnt = new Point() { Lat = d.usrLat, Lon = d.usrLong };
}
else inc++;
}
return pnt;
}