Global instances of class

好久不见. 提交于 2019-12-09 00:18:09

问题


Still trying to get to know C# (Mostly worked with C). I have a class "Device" and would like to create an instance of the class, but would also like access to the instances globally because I use them so much in my GUI methods.

 public class Device
    {
        public string Name;
        public List<string> models = new List<string>();
        public List<string> revisions = new List<string>();
        ...
    }

Somehow declare this globally:

 Device Device1 = new Device();
 Device1.Name = "Device1";

Then access it later in a WPF method:

 private void DeviceViewItem_Selected(object sender, RoutedEventArgs e)
    {
       TreeViewItem selected = (TreeViewItem)sender;

        if (selected.Name == Device1.Name)
        {
            Device1.Models.Add("something");
            Device1.Revisions.Add("something");
        }

I've been reading about singleton Pattern, but it looks like you have to create a Singleton Class, but my "Device" Class is used multiple times to create many devices. Maybe I just don't understand the pattern that well.


回答1:


Create a new instance and assign it to a static property or field:

public class AnyClass
{
    public static readonly Device ThisFieldCanBeReachedFromAnywhere = new Device();
}

Note that the class AnyClass doesn't have to be static (that would however mean that all members must be static).

Also note that the readonly keyword isn't required, it is just good practice for singletons (like Mark suggested in his comment).



来源:https://stackoverflow.com/questions/17555620/global-instances-of-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!