我在返回类型元素处收到编译错误, 错误是并非所有代码路径都返回一个值。
我正在返回整数值。我在哪里弄错了?我的 代码
public int InsertUserData(UserDetail userDetail, BusinessObjects objects,PersonalData newPersonal,EducationalData newEducational,ContactData newContact)
{
try
{
UserCredential objCredentials;
int result=1;
if (objects.Status==1)
{
objCredentials = newPersonEntity.UserCredentials
.First(cd => cd.UserName == objects.UserName);
objCredentials.Status = objects.Status;
newPersonEntity.UserDetails.Add(userDetail);
result = newPersonEntity.SaveChanges();
return result;
}
else if (objects.Status == 2)
{
switch (objects.FormId)
{
case 1:
objCredentials = newPersonEntity.UserCredentials
.First(cd => cd.UserName == objects.UserName);
objCredentials.Status = objects.Status;
newPersonEntity.PersonalDatas.Add(newPersonal);
result = newPersonEntity.SaveChanges();
break;
case 2:
objCredentials = newPersonEntity.UserCredentials
.First(cd => cd.UserName == objects.UserName);
objCredentials.Status = objects.Status;
newPersonEntity.EducationalDatas.Add(newEducational);
result = newPersonEntity.SaveChanges();
break;
case 3:
objCredentials = newPersonEntity.UserCredentials
.First(cd => cd.UserName == objects.UserName);
objCredentials.Status = objects.Status;
newPersonEntity.ContactDatas.Add(newContact);
result = newPersonEntity.SaveChanges();
break;
default:
break;
}
return result;
}
}
catch (Exception ex)
{
CatchError(ex);
return 3;
}
}
有谁能告诉我我在代码中犯了什么错误?
答案 0 :(得分:1)
如果objects.Status==1
和objects.Status==2
,则返回值,但如果objects.Status具有其他值,则返回任何值。所以我建议你返回默认值,如
else
{
return 0; // or any other value
}
并且您的新代码将是
public int InsertUserData(UserDetail userDetail, BusinessObjects objects,PersonalData newPersonal,EducationalData newEducational,ContactData newContact)
{
try
{
UserCredential objCredentials;
int result=1;
if (objects.Status==1)
{
objCredentials = newPersonEntity.UserCredentials
.First(cd => cd.UserName == objects.UserName);
objCredentials.Status = objects.Status;
newPersonEntity.UserDetails.Add(userDetail);
result = newPersonEntity.SaveChanges();
return result;
}
else if (objects.Status == 2)
{
switch (objects.FormId)
{
case 1:
objCredentials = newPersonEntity.UserCredentials
.First(cd => cd.UserName == objects.UserName);
objCredentials.Status = objects.Status;
newPersonEntity.PersonalDatas.Add(newPersonal);
result = newPersonEntity.SaveChanges();
break;
case 2:
objCredentials = newPersonEntity.UserCredentials
.First(cd => cd.UserName == objects.UserName);
objCredentials.Status = objects.Status;
newPersonEntity.EducationalDatas.Add(newEducational);
result = newPersonEntity.SaveChanges();
break;
case 3:
objCredentials = newPersonEntity.UserCredentials
.First(cd => cd.UserName == objects.UserName);
objCredentials.Status = objects.Status;
newPersonEntity.ContactDatas.Add(newContact);
result = newPersonEntity.SaveChanges();
break;
default:
break;
}
return result;
}
else
{
return 0; // or any other value
}
}
catch (Exception ex)
{
CatchError(ex);
return 3;
}
}