简体   繁体   English

C# - 静态嵌套类

[英]C# - Static nested classes

I have two classes which I want to access from any part of Windows Forms application.我有两个类,我想从 Windows 窗体应用程序的任何部分访问它们。 How to add a couple of Participants and how to referce them?如何添加几个参与者以及如何引用它们? The idea is this:这个想法是这样的:

//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; }
}

maybe there is some better way to do it?也许有更好的方法来做到这一点?

You are probably misusing the static keyword.您可能误用了 static 关键字。 Static use is to have all instances of one class share the same values.静态使用是让一个类的所有实例共享相同的值。 Here the state of a participant would be the same for every participant.在这里,参与者的状态对于每个参与者都是相同的。

Try just removing the static keyword from your participants and you are probably done.尝试从您的参与者中删除 static 关键字,您可能就完成了。

I would suggest the Singleton-pattern for this which enables you to have only one single instance of a class per app-domain .我会为此建议使用Singleton-pattern ,它使您可以在每个 app-domain 中只有一个类的单个实例 This way you don´t need any static at all, just get the single instance and call any of its members:这样你根本不需要任何static ,只需获取单个实例并调用其任何成员:

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

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

Now you can just use this code fom anywhere in your program:现在你可以在你的程序的任何地方使用这个代码:

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

Just remove the static modifier from Participant class properties.只需从 Participant 类属性中删除静态修饰符。 Being static will make them unrelated to the defiend instances and cannot be called like this:静态将使它们与防御实例无关,并且不能像这样调用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM