使整个应用程序访问(可以在运行时改变)数据的最佳方式? [英] Best way to make data (that may change during run-time) accessible to the whole application?

查看:92
本文介绍了使整个应用程序访问(可以在运行时改变)数据的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是有throughtout的沃莱·应用程序访问数据的最佳方式?在我的具体的例子,我从一个XML文件,我的应用程序的设置加载到设置对象的实例,我不想让这些绝对的一些常数,因为用户应该能够改变这些(和看到效果)而无需重新启动该程序。

what is the best way to have data accessible throughtout the wole application? In my concrete example I load the settings of my application from an XML file into an instance of a Settings-Object, and I don't want to make these some absolute constants because the user should be able to change these (and see the effects) without restarting the program.

现在,我需要使用某些其他类的方法)设置(属性,但这种方式他们无法访问。因此,在什么样的一个'对象'我应该保存设置?我不认为这是很好的它每一个需要设置在我的应用程序寻找到XML本身的方法。此外,通过设置实例到我利用一切其他阶级似乎太麻烦了。

Now, I need to use certain of the (properties of the) settings in methods of other classes, but in this way they are not accessible. So in what kind of an 'Object' should I store the settings? I don't think it is good it each method that needs a setting across my application has to look into the XML itself. Also, passing the settings instance into every other class I use seems too cumbersome.

在此先感谢!

推荐答案

在C#中,我总是使用一个静态类来提供此功能。静态类中详细介绍这里 ,但简要地说它们只包含静态成员,不实例化的 - 本质上他们是通过他们的类名访问的全局函数和变量

In C# I always use a static classes to provide this functionality. Static classes are covered in detail here, but briefly they contain only static members and are not instantiated -- essentially they are global functions and variables accessed via their class name (and namespace.)

下面是一个简单的(和命名空间)。例如:

Here is a simple example:

public static class Globals
{
    public static string Name { get; set; }
    public static int aNumber {get; set; }
    public static List<string> onlineMembers = new List<string>();

     static Globals()
     {
        Name = "starting name";
        aNumber = 5;
     }
}

请注意,我还使用一个静态初始化它。保证在某些时候使用/被叫之前的任何成员或函数运行

Note, I'm also using a static initializer which is guaranteed to run at some point before any members or functions are used / called.

在别处在你的程序,你可以简单地说:

Elsewhere in your program you can simply say:

Console.WriteLine(Globals.Name);
Globals.onlineMemeber.Add("Hogan");






要重新状态的反应发表评论,静对象不仅是创造一次。因此到处应用程序使用对象将是从同一位置。它们是由定义全球。要使用多个地方这个对象只需简单地引用对象的名称和您要访问的元素。


To re-state in response to comment, static objects are only "created" once. Thus everywhere your application uses the object will be from the same location. They are by definition global. To use this object in multiple places simply reference the object name and the element you want to access.

这篇关于使整个应用程序访问(可以在运行时改变)数据的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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