2017-08-10 107 views
-2

你好我有很多變量,正如我在下面提到的,但是當我改變一個變量的值時,這個變化不會被使用這個變量的變量調整。C#不斷更新變量

class PublicVariable 
{ 
    public static string ActiveUser = UserInfo.Username; 
    public static string ActiveUserPath = [email protected]"{Application.StartupPath}\{ActiveUser}"; 
    public static string ActiveUserImg = [email protected]"{ActiveUserPath}\User.png"; 
} 
class UserInfo 
{ 
    public static string Username = "-1064548"; //Working 
} 
class Starting 
{ 
    public void Login(string Username, string Pwd) 
    { 
     //After the user logged in. 
     UserInfo.Username = "BruceWayne"; //Working 
     /* Showing -1064548 = */ MessageBox.Show(PublicVariable.ActiveUser.ToString()); //Not Working. 
    } 
} 

爲了簡化代碼,ActiveUser就是一個例子。 該代碼序列就是一個例子。目標是從數據庫中獲取數據一次。

+1

將** PublicVariable.ActiveUser **變量轉換爲像這樣的屬性:'public static string ActiveUser => UserInfo.Username;' –

+4

爲什麼要這樣做。您**將'UserInfo.Username'的**值**分配給'ActiveUser'字段。當您稍後更改'UserInfo.Username'中的值時,爲什麼'ActiveUser'中的值應該改變? –

+0

你永遠不會改變PublicVariable.ActiveUser的值。當你在類中定義它時,你並沒有創建一個指針 - 你正在給它賦值。 –

回答

0

爲了解決你的問題,我建議在這裏使用屬性。這應該是這樣的,那麼:

class PublicVariable 
{ 
    public static string ActiveUser => UserInfo.Username; 
    public static string ActiveUserPath => [email protected]"{Application.StartupPath}\{ActiveUser}"; 
    public static string ActiveUserImg => [email protected]"{ActiveUserPath}\User.png"; 
} 

class UserInfo 
{ 
    public static string Username = "-1064548"; //Working 
} 

class Starting 
{ 
    public void Login (string Username, string Pwd) 
    { 
     UserInfo.Username = "BruceWayne"; 
     MessageBox.Show (PublicVariable.ActiveUser.ToString()); 
    } 
} 

另外,您可以使用方法,以及:

class PublicVariable 
{ 
    public static string ActiveUser() => UserInfo.Username; 
    public static string ActiveUserPath() => [email protected]"{Application.StartupPath}\{ActiveUser()}"; 
    public static string ActiveUserImg() => [email protected]"{ActiveUserPath()}\User.png"; 
} 

class UserInfo 
{ 
    public static string Username = "-1064548"; //Working 
} 

class Starting 
{ 
    public void Login (string Username, string Pwd) 
    { 
     UserInfo.Username = "BruceWayne"; 
     MessageBox.Show (PublicVariable.ActiveUser().ToString()); 
    } 
} 

實際上有沒有屬性和方法之間的主要區別。但是,字段(您使用它們)是不同的,因爲它們在依賴值更改時不會更新它們的值。這意味着,只要您沒有對其他值的引用(對象的情況,就像您的類Starting的對象那樣),字段值不會更新。

+0

謝謝你的回覆,我的問題已經很快解決了。 – Emre