类的全局实例 [英] Global instances of class

查看:92
本文介绍了类的全局实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍在试图了解C#(用C晴的了)。我有一个类设备,并想创建类的实例,但也想进入全球性的实例,因为我使用他们这么多我的GUI方法。

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";



后来的后来访问它在WPF方法:

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");
        }



我一直在阅读有关Singleton模式,但它看起来像你必须创建一个Singleton类,但我的设备类用于多次创建多个设备。也许我只是不明白该模式的好。

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.

推荐答案

创建一个新的实例,并将其分配到的 静态 属性或字段:

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

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

请注意,类AnyClass不必是静态的(但是该会意味着所有成员的必须是静态的)。

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).

这篇关于类的全局实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆