抱歉不得不問一個看起來很愚蠢的問題,但我試了最後至少5小時的所有建議。它並沒有使它更清晰。 我是一個初學者程序員,我不知道爲什麼它不工作,沒有編譯錯誤,所以我需要你的幫助。List.Contains code not working,spent hours reading still still do it
我認爲這個問題是在list.Contains部分,因爲一切似乎工作,但IDK的
我的最終目標是有幾分本地註冊/登錄系統(而無需使用任何數據庫或SQL的東西)
下面是代碼:
class CustomerList
{
private string _x = "x";
private string _y = "y";
private string _x2 = "x2";
private string _y2 = "y2";
private List<Customer> _list;
//
public string Username
{
get { return _x; }
set { _x = value; }
}
// these are for the register
public string Password
{
get { return _y; }
set { _y = value; }
}
//
public CustomerList()
{
_list = new List<Customer>();
}
//
public string Username2
{
get { return _x2; }
set { _x2 = value; }
}
//these are for the login
public string Password2 {
get { return _y2; }
set { _y2 = value; } }
//
public void Register()
{
_list.Add(new Customer { Name = Username, Pass = Password });
}
public void Login()
{
if (_list.Contains(new Customer {Name = Username2, Pass = Password2}))
CanLogin = true;
}
public bool CanLogin { get; set; } = false;
}
namespace App10.Model
{
public class Customer : IEquateable<Customer>
{
private string _password = "";
private string _username = "";
public Customer()
{
}
public Customer(string username, string password)
{
this.Pass = password;
this.Name = username;
}
public string Name
{
get { return _username; }
set { _username = value; }
}
public string Pass
{
get { return _password; }
set { _password = value; }
}
public bool Equals(Customer other)
{
if (other == null)
return false;
if (this._username == other._username)
return true;
else
return false;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
Customer customerObj = obj as Customer;
if (customerObj == null)
return false;
else
return Equals(customerObj);
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
public static bool operator ==(Customer person1, Customer person2)
{
if (((object)person1) == null || ((object)person2) == null)
return Object.Equals(person1, person2);
return person1.Equals(person2);
}
public static bool operator !=(Customer person1, Customer person2)
{
if (((object)person1) == null || ((object)person2) == null)
return !Object.Equals(person1, person2);
return !(person1.Equals(person2));
}
}
public interface IEquateable<T>
{
}
}
private void register_Click_1(object sender, RoutedEventArgs e)
{
CustomerList ss = new CustomerList();
ss.Username = textBox.Text;
ss.Password = textBox1.Text;
ss.Register();
Frame.Navigate(typeof(BlankPage2));
}
private void login_Click(object sender, RoutedEventArgs e)
{
CustomerList ss2 = new CustomerList();
ss2.Login();
if (ss2.CanLogin)
{
Frame.Navigate(typeof(MainPage));
}
您不想使用'Contains',使用'Any',像這樣'_list .Any(c => c.Name ==「name」&& c.Pass =「pass」);'。這樣你就不需要重寫'=='和其他所有的絨毛。 – DavidG