繁体   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