全局类访问变量 [英] Global Class to access Variables

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

问题描述

我们希望拥有一个类的全局实例,并希望在整个应用程序中进行访问(以不同的形式等)

有哪些不同的可能性? (不是静态类).

We like to have a global instance of a class and would like to access across the application (in different forms etc)

What are the different possiblities? (other than static class).

推荐答案

除非所有静态形式都可以访问静态类,除非您创建非静态类的实例并传递引用到您认为可能需要访问的所有表格.

但是,几乎没有这个,几乎每个C#程序都可以很好地管理.您要达到什么目的,以为您需要一个充满变量的全局类?
Only a static class will be accessible across all forms, unless you create an instance of a non-static class and pass the reference to that to all the forms you think are likely to need access.

However, nearly every C# program manages very nicely without this. What are you trying to achieve that you think needs a global class chock-full of variables?


如果确实需要全局访问单个实例,请使用Singleton模式.
http://msdn.microsoft.com/en-us/library/ff650316.aspx [ ^ ].
If you really need global access to a single instance, use the Singleton pattern.
http://msdn.microsoft.com/en-us/library/ff650316.aspx[^].


这是在没有静态类的情况下实现 singleton 行为的方法之一:

This is one of the ways to implement singleton behavior without having a static class:

class Singleton {
    public Singleton() { } //prevent instantiation from outside
    public static Singleton Instance {
        get {
            if (SingleInstance == null) //keep it lazy
                SingleInstance = new Singleton();
            return SingleInstance;
        }
    }
    public int FirstProperty { get; set; }
    public string SecondProperty { get; set; }
    public void Run() { /*...*/ }
    //...
    private static Singleton SingleInstance;
}



如果通过静态Singleton.Instance执行所有访问,则可以保证全局访问和唯一性(使用Application Domain).

对于静态数据,在有多个线程可以访问单例的情况下,使用锁定来确保线程安全非常重要.
或者,可以使用 volatile 关键字.
请参阅: http://msdn.microsoft.com/en-us/library /x13ttww7(v=VS.100).aspx [ ^ ], http://www.dotnetperls.com/volatile [^ ].

—SA



All access if performed via static Singleton.Instance which guarantee both global access and uniqueness (withing Application Domain).

For static data it''s very important to secure thread safety using locking, in case of more than one thread having access to the singleton.
Alternatively, volatile keyword can be used.
See: http://msdn.microsoft.com/en-us/library/x13ttww7(v=VS.100).aspx[^], http://www.dotnetperls.com/volatile[^].

—SA


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

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