Skip to content

Instantly share code, notes, and snippets.

@chitoku-k
Created November 21, 2014 09:09
Show Gist options
  • Save chitoku-k/1dd7ffe1b373759aaee7 to your computer and use it in GitHub Desktop.
Save chitoku-k/1dd7ffe1b373759aaee7 to your computer and use it in GitHub Desktop.
XML で設定読み書きするやつ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace TestApp
{
public class Program
{
static void Main(string[] args)
{
var s = new TestSetting();
// 読み込み or 新規作成
TestSetting.Load("setting.xml");
// 取得
var uris = TestSetting.Instance.Uris;
// 設定
TestSetting.Instance.Uris = new List<UrlPair>();
TestSetting.Instance.Uris.Add(new UrlPair("Google", "http://google.co.jp/"));
TestSetting.Instance.Uris.Add(new UrlPair("Yahoo", "http://yahoo.co.jp/"));
TestSetting.Instance.Uris.Add(new UrlPair("Twitter", "http://twitter.com/"));
// 保存
s.Save("setting.xml");
}
}
}
using System;
using System.IO;
using System.Xml.Serialization;
namespace TestApp
{
[Serializable]
public abstract class SettingsBase<T>
// 型 "T" が new を呼ぶことができる型のみ、と限定
// 「new 制約」[検索]
where T : new()
{
// 設定へのインスタンス
public static T Instance { get; set; }
// シリアライザ
private static readonly XmlSerializer Serializer = new XmlSerializer(typeof(T));
// 設定の読み込み
public static void Load(string path)
{
if (File.Exists(path))
{
using (var reader = new StreamReader(path))
{
Instance = (T)Serializer.Deserialize(reader);
}
}
else
{
Instance = new T();
}
}
// 設定の書き込み
public void Save(string path)
{
using (var writer = new StreamWriter(path))
{
Serializer.Serialize(writer, Instance);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestApp
{
// SettingsBase<T> を継承して使う
// <T> には作るクラスの名前を入れる
public class TestSetting : SettingsBase<TestSetting>
{
public List<UrlPair> Uris { get; set; }
}
}
using System;
namespace TestApp
{
[Serializable]
public class UrlPair
{
public string Name { get; set; }
public string Url { get; set; }
// 空のコンストラクター
public UrlPair() { }
public UrlPair(string name, string url)
{
this.Name = name;
this.Url = url;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment