简体   繁体   中英

C# - Static nested classes

I have two classes which I want to access from any part of Windows Forms application. 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 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.

I would suggest the Singleton-pattern for this which enables you to have only one single instance of a class per app-domain . This way you don´t need any static at all, just get the single instance and call any of its members:

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. Being static will make them unrelated to the defiend instances and cannot be called like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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