How do I make an object persistent in memory while application is running?

I've an object like this:

public class Parents
{
    public List<Parent> {get; set;}
}
public class Parent
{
    public string name {get; set;}
    public int age {get; set;}
    public List<Child> {get; set;}
}
public class Child
{
    public string name {get; set;}
    public int age {get; set;}
}

after filling "Parents" with multiple "Parent" and each of them with multiple "Child" from an xml, i'd like to make them persistent (in memory only), so I might call it from every part of my program without the need of recreating them or sending them from one part of my code to another. Also i'd like to do the same, with a DataSet.

I'm aware of that "persistent" might be the wrong word in this context, but I have no idea how else to call it, so please let me know if there is a better term.


You can create a class to hold the state.

public static class GlobalConfiguration
{
    public Parents Parents { get; set; }
}

More generic if you plan to hold many objects:

public static class GlobalConfiguration
{
    static GlobalConfiguration()
    {
        Objects = new Dictionary<string, object>();
    }

    public readonly IDictionary<string, object> Objects { get; set; }
}

Usage:

object parentsObject;

if(GlobalConfiguration.Objects.TryGetValue("Parents", out parentsObject))
{
    var parents = parentsObject as Parents;
    // use parents
}

However, the "I might call it from every part of my program[...]" hints that you want something to manage the dependencies of your various components versus global state.

For that you should look into dependency injection.

See also:

  • Globals vs dependency injection
  • Why does one use dependency injection?
  • Which .NET Dependency Injection frameworks are worth looking into?

  • You could use a static property

    http://msdn.microsoft.com/en-us/library/vstudio/98f28cdx.aspx


    I'd suggest using the Singleton pattern in this scenario: you want one instance of this throughout your application and the singleton pattern provides exactly that.

    EDIT
    I'd be remiss if I didn't point out Jon Skeet's very nice implementation of the Singleton pattern.

    链接地址: http://www.djcxy.com/p/82248.html

    上一篇: 依赖注入是否会导致额外的内存消耗?

    下一篇: 如何在运行应用程序时使对象在内存中保持持久性?