Ale*_*key 1 c# methods for-loop return
此代码将比较存储在文本文件中的用户名和密码.我认为这是因为for循环,它可能很简单但我无法看到它.
public int loginCheck()
{
//-----------------------------------------------------------------
string[] users = File.ReadLines("Username_Passwords").ToArray();
//line of text file added to array
//-----------------------------------------------------------------
for (int i = 0; i < users.Length; i++)
{
string[] usernameAndPassword = users[i].Split('_');
//usernames and passwords separated by '_' in file, split into two strings
if (_username == usernameAndPassword[0] && _password == usernameAndPassword[1])
{
return 1;
//return 1, could have used bool
}
else
{
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
如果users是空数组,则不返回任何值.
string[] users = File.ReadLines("Username_Passwords").ToArray();
// if users is empty, users.Length == 0 and the loop isn't entered
for (int i = 0; i < users.Length; i++)
{
...
}
// no value is returned
return 0; // <- suggested amendment
Run Code Online (Sandbox Code Playgroud)
可能,你必须return 0;在循环下面添加
作为进一步的改进,您可以使用Linq重写该方法(1如果文件包含任何具有所需用户名和密码的记录,0则返回),否则:
public int loginCheck() {
return File
.ReadLines("Username_Passwords")
.Select(line => line.Split('_'))
.Any(items => items.Length >= 2 &&
items[0] == _username &&
items[1] == _password)
? 1
: 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
290 次 |
| 最近记录: |