C#-静态嵌套类
我想从Windows窗体应用程序的任何部分访问两个类。如何添加几个参与者以及如何推荐他们? 这个想法是:C#-静态嵌套类,c#,oop,C#,Oop,我想从Windows窗体应用程序的任何部分访问两个类。如何添加几个参与者以及如何推荐他们? 这个想法是: //add participants Dialog.Participants.Add(new Participant { state = "" }); //modify state Dialog.Participants[0].state = ... public class Dialog { public static string state { get; set; }
//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; }
}
//添加参与者
添加(新参与者{state=”“});
//修改状态
对话框。参与者[0]。状态=。。。
公共类对话框
{
公共静态字符串状态{get;set;}
公共静态列表参与者{get;set;}
}
公开课参与者
{
公共静态字符串状态{get;set;}
公共静态列表操作{get;set;}
}
也许有更好的方法吗?您可能误用了static关键字。静态用法是让一个类的所有实例共享相同的值。在这里,每个参与者的状态都是相同的 尝试从参与者中删除static关键字,您可能已经完成了。我建议使用此选项,这样每个应用程序域只能有一个类实例。这样,您根本不需要任何
静态,只需获取单个实例并调用其任何成员:
public class Dialog
{
private readonly static _instance = new Dialog();
public static Instance { get { return _instance; }}
public List<Participant> Participants { get; set; }
}
只需从参与者类属性中删除静态修饰符。静态将使它们与Defined实例无关,不能这样调用:
Dialog.Participants[0].state = ...
您可以从任何地方访问公共类和成员。但是,您需要对它们的实例进行引用。如果您只需要一个实例,请使用singleton模式,而不是依赖静态类?这和标题有什么关系?(首先,我当然建议您开始遵循.NET命名约定。而且看起来您永远不会创建新的列表
。)您需要创建类的实例,并通过将变量名放在方法之外使实例全局化。您可能还希望将变量设置为静态的。你认为单例相对于静态类有什么好处?2.您的单例实现可以而且应该得到改进。请深入阅读来自C#的Jon Skeet的文章。
Dialog.Participants[0].state = ...