簡體   English   中英

C# - 靜態嵌套類

[英]C# - Static nested classes

我有兩個類,我想從 Windows 窗體應用程序的任何部分訪問它們。 如何添加幾個參與者以及如何引用它們? 這個想法是這樣的:

//add participants
Dialog.Participants.Add(new Participant { state = "" });
//modify state
Dialog.Participants[0].state = ...


public class Dialog
{
    public static string state { get; set; }
    public static List<Participant> Participants { get; set; }
}

public class Participant
{
    public static string state { get; set; }
    public static List<string> actions { get; set; }
}

也許有更好的方法來做到這一點?

您可能誤用了 static 關鍵字。 靜態使用是讓一個類的所有實例共享相同的值。 在這里,參與者的狀態對於每個參與者都是相同的。

嘗試從您的參與者中刪除 static 關鍵字,您可能就完成了。

我會為此建議使用Singleton-pattern ,它使您可以在每個 app-domain 中只有一個類的單個實例 這樣你根本不需要任何static ,只需獲取單個實例並調用其任何成員:

public class Dialog
{
    private readonly static _instance = new Dialog();
    public static Instance { get { return _instance; }}

    public List<Participant> Participants { get; set; }
}

現在你可以在你的程序的任何地方使用這個代碼:

Dialog.Instance.Participants[.}.state ? ...

只需從 Participant 類屬性中刪除靜態修飾符。 靜態將使它們與防御實例無關,並且不能像這樣調用:

Dialog.Participants[0].state = ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM