wpf 类的全局实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17555620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:11:08  来源:igfitidea点击:

Global instances of class

c#wpfclasssingletoninstance

提问by DevynB

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.

仍在尝试了解 C#(主要使用 C)。我有一个“Device”类,想创建该类的一个实例,但也想全局访问这些实例,因为我在 GUI 方法中经常使用它们。

 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:

然后稍后在 WPF 方法中访问它:

 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.

我一直在阅读关于单例模式,但看起来你必须创建一个单例类,但是我的“设备”类被多次使用来创建许多设备。也许我只是不太了解模式。

回答by lightbricko

Create a new instance and assign it to a staticproperty 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 mustbe static).

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

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

还要注意, readonly 关键字不是必需的,它只是单身人士的好习惯(就像马克在他的评论中建议的那样)。