[英]How to access object from another form c#
因此,我有一個名為Employee的類,用於存儲員工的用戶名和密碼。
class Employee
{
string username;
string password;
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public Employee(string username, string password)
{
this.username = username;
this.password = password;
}
在我的主類中,我創建了Employee實例和一些示例數據。
Employee employee1 = new Employee("John", "123");
我將這段代碼包含在main方法中,以根據用戶名和密碼對用戶進行身份驗證。
do
{
Console.Write("Username: ");
username = Console.ReadLine();
Console.Write("Password: ");
password = Console.ReadLine();
if (employee1.Username != username || employee1.Password != password)
{
Console.WriteLine("Incorrect Username or Password. Please Try again \n");
}
}
while (employee1.Username != username || employee1.Password != password);
Console.Clear();
Console.Write("Login Sucessful!. Press any key to continue...");
Console.ReadKey();
我不想在主類中包含這段代碼,而是要在Employee.cs中傳輸此代碼,該方法充當方法,可以從主類中調用。 我的問題是,如何從主類訪問對象,並獲取初始化的用戶名和密碼,以在Employee.cs上應用相同的概念。
您的意思是:
class Employee
{
// Existing code above this
public bool Authenticate()
{
var authed = false;
do
{
Console.Write("Username: ");
var attemptUsername = Console.ReadLine();
Console.Write("Password: ");
var attemptPassword = Console.ReadLine();
if (username != attemptUsername || password != attemptPassword)
{
Console.WriteLine("Incorrect Username or Password. Please Try again \n");
}
else
{
authed = true;
}
}
while (!authed);
Console.Clear();
Console.Write("Login Sucessful!. Press any key to continue...");
Console.ReadKey();
return authed;
}
}
然后您可以去:
var john = new Employee("John", 123);
john.Authenticate(); // Waits until he enters valid password (Might want to add a max attempts to the Authenticate function and actually use the return value
注意:根據您使用的框架等,通常最好將Employee / Veternerian
類保留為POCO,並使用服務基於它們添加邏輯。
這是你要找的嗎?
class Mainclass
{
Main()
{
Employee employee1 = new Employee("John", "123");
employee1.yourMethod();
}
}
public class Employee
{
string username;
string password;
.
.
.
public void yourMethod()
{
do
{
Console.Write("Username: ");
username = Console.ReadLine();
Console.Write("Password: ");
password = Console.ReadLine();
if (veterinarian1.Username != username || veterinarian1.Password != password)
{
Console.WriteLine("Incorrect Username or Password. Please Try again \n");
}
}
while (veterinarian1.Username != username || veterinarian1.Password != password);
Console.Clear();
Console.Write("Login Sucessful!. Press any key to continue...");
Console.ReadKey();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.