Infinite Loop? Can't see why
I have a function that takes in a roleID(as an int)
, and compares it to a multidimensional array to see if that array contains that roleID
. if it开发者_C百科 does, it sets a bool to true and breaks. if it doesn't, the loop never exits. I'm hoping this is something stupid that I'm overlooking, but I've had a few different people look it over now.
The size of the userRoles array
that I am testing with right now is 3
. I can print userRoles.GetLength(0)
and it says 3, and that matches whats in the database.
here's the code:
public bool IsInRole(int roleID)
{
bool inRole = false;
int i = userRoles.GetLength(0);
for (int j = 0; j < i; j++)
{
if (Convert.ToInt32(userRoles[j, 0]) == roleID)
{
inRole = true;
break;
}
}
return inRole;
}
TIA,
ChrisAre you sure that you're not misdiagnosing the symptom, and that it really is getting stuck in the loop? The code you have there doesn't look like wrong, my first thought would be that the place that you're calling IsInRole() isn't handling a 'false' return correctly.
Is j actually incrementing? or is it somehow being reset it back to 0?
Try this
public bool IsInRole(int roleID)
{
bool inRole = false;
int i = userRoles.GetLength(0);
for (int j = 0; j < i; j++)
{
int k = j;
if (Convert.ToInt32(userRoles[k, 0]) == roleID)
{
inRole = true;
break;
}
}
return inRole;
}
Looking at MSDN's GetLength property, to quote 'An example of GetLength is GetLength(0), which returns the number of elements in the first dimension of the Array.'
public bool IsInRole(int roleID) { bool inRole = false; try{ int i = userRoles.GetLength(0); for (int j = 0; j < i; j++) { if (Convert.ToInt32(userRoles[j, 0]) == roleID) { inRole = true; break; } } }catch(Exception up){ throw up; } return inRole; }
I would be inclined to wrap the logic into a try/catch to see if the Convert.ToInt32
or GetLength(0)
is throwing an exception...
Hope this helps, Best regards, Tom.
Your loop looks solid so it must be not exiting for a different reason. Could your array contain a value that would cause Convert.ToInt32 to hang or throw?
精彩评论