为什么这段代码不能编译?
它给了我错误:
并非所有代码路径都返回值
public bool isUserProfileHashed(string username)
{
bool isHashed = false;
MembershipUser u = null;
u = Membership.GetUser(username);
if (u != null)
{
try
{
u.GetPassword();
}
catch (Exception exception)
{
// An exception is thrown when the GetPassword method is called for a user with a hashed password
isHashed = true;
return isHashed;
}
return isHashed;
}
答案 0 :(得分:10)
你忘了把if的返回放在之外,把它放在if结束的大括号之后
public bool isUserProfileHashed(string username)
{
bool isHashed = false;
MembershipUser u = null;
u = Membership.GetUser(username);
if (u != null)
{
try
{
u.GetPassword();
}
catch
{
// An exception is thrown when the GetPassword method is called for a user with a hashed password
isHashed = true;
}
}
return isHashed;
}
<强> [编辑] 强>
删除不必要的退货(@FredrikMörk)
未使用的捕获异常因此也将其删除。
答案 1 :(得分:1)
if块之外没有return语句。有时候if块可能无法执行。
答案 2 :(得分:1)
如果你是null,则不返回。
答案 3 :(得分:1)
如果u == null,则整个if语句将跳过。 if语句之外没有return语句。
这就是为什么你看到“并非所有代码路径都返回值。”
只需在if块之后添加一个return语句:
public bool isUserProfileHashed(string username)
{
bool isHashed = false;
MembershipUser u = null;
u = Membership.GetUser(username);
if (u != null)
{
// ...
return isHashed;
}
// more code here if you need it
return ??? ; // <--- **ADD THIS**
}
答案 4 :(得分:1)
您没有处理u == null
的情况,并且如果满足该条件则返回值。
答案 5 :(得分:1)
如果你碰巧 null ,则不会返回!
这应该效果更好
public bool isUserProfileHashed(string username)
{
bool isHashed = false;
MembershipUser u = null;
u = Membership.GetUser(username);
if (u != null)
{
try
{
u.GetPassword();
}
catch (Exception exception)
{
// An exception is thrown when the GetPassword method is called for a user with a hashed password
isHashed = true;
return isHashed;
}
return isHashed;
}
else
{
//Throw or return false, whatever
throw new Exception("Could not get user ...");
}
}
答案 6 :(得分:1)
其他海报已经注意到对您的方法的修正,但是,是否可以用这条线替换整个方法?
if(Membership.Provider.PasswordFormat == MembershipPasswordFormat.Hashed)