Page 1 of 1

[tip] Jednoduchý přístup na IsolatedStorage

Posted: Sun Sep 25, 2011 17:57
by Martin Suchan
Chtěl bych se podělit o chytrý a jednoduchý přístup, jak v aplikacích ukládat data do IsolatedStorage - tento wrapper má pár řádků a osvědčil se mi ve všech aplikacích, co zatím mám. Statická třída Settings slouží jako wrapper ukládaných hodnot, však není třeba popisovat, jen to vyzkoušejte :)

Odkaz na PasteBin
http://pastebin.com/xQ0wcttA" onclick="window.open(this.href);return false;

Code: Select all

using System.IO.IsolatedStorage;

namespace Helper
{
    public static class Settings
    {
        // Persistent user settings from the settings page
        public static readonly Setting<string> CurrentUser = new Setting<string>("CurrentUser", "user1");
        public static readonly Setting<int> CurrentScore = new Setting<int>("CurrentScore", 0);
        public static readonly Setting<GameState> LevelState = new Setting<GameState>("LevelState", new GameState());
    }

    // Encapsulates a key/value pair stored in Isolated Storage ApplicationSettings
    public class Setting<T>
    {
        private readonly string name;
        private T value;
        private readonly T defaultValue;
        private bool hasValue;

        public Setting(string name, T defaultValue)
        {
            this.name = name;
            this.defaultValue = defaultValue;
        }

        public T Value
        {
            get
            {
                // Check for the cached value
                if (!hasValue)
                {
                    // Try to get the value from Isolated Storage
                    if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue(name, out value))
                    {
                        // It hasn’t been set yet
                        value = defaultValue;
                        IsolatedStorageSettings.ApplicationSettings[name] = value;
                    }
                    hasValue = true;
                }
                return value;
            }
            set
            {
                // Save the value to Isolated Storage
                IsolatedStorageSettings.ApplicationSettings[name] = value;
                this.value = value;
                hasValue = true;
            }
        }

        public T DefaultValue
        {
            get { return defaultValue; }
        }

        // “Clear” cached value:
        public void ForceRefresh()
        {
            hasValue = false;
        }
    }
}