Skip to content

Instantly share code, notes, and snippets.

@htsign
Last active August 29, 2015 14:16
Show Gist options
  • Save htsign/efd59d61c5329aa0b8c3 to your computer and use it in GitHub Desktop.
Save htsign/efd59d61c5329aa0b8c3 to your computer and use it in GitHub Desktop.
MusicBeeプラグイン作成に利用しているConfigクラスとその基底クラス
using System;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
namespace MusicBeePlugin
{
public class ConfigBase
{
/// <summary>
/// デフォルト値を読み込みます。
/// </summary>
public void LoadDefault()
{
var type = this.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo prop in properties)
{
// XmlIgnore属性が付与されている場合は無視
if (prop.HasAttribute<XmlIgnoreAttribute>()) continue;
// 各プロパティに[Default***]を代入する
FieldInfo defaultField = type.GetField("Default" + prop.Name, BindingFlags.Instance | BindingFlags.NonPublic);
if (defaultField != null)
{
object defaultValue = defaultField.GetValue(this);
prop.SetValue(this, defaultValue, null);
}
}
}
/// <summary>
/// 指定されたパスに設定をXMLシリアライズして保存します。
/// </summary>
/// <param name="path"></param>
public void Save(string path)
{
var serializer = new XmlSerializer(this.GetType());
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
serializer.Serialize(fs, this);
}
}
/// <summary>
/// 指定されたパスからXMLを取得し、デシリアライズして設定を読み込みます。
/// </summary>
/// <param name="path"></param>
public void Load(string path)
{
if (!File.Exists(path))
{
this.LoadDefault();
return;
}
var serializer = new XmlSerializer(this.GetType());
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
try
{
var config = (ConfigBase)serializer.Deserialize(fs);
PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo prop in properties)
{
object newValue = prop.GetValue(config, null);
prop.SetValue(this, newValue, null);
}
}
catch (InvalidOperationException)
{
this.LoadDefault();
}
}
}
}
[Serializable]
public class Config
: ConfigBase
{
private Config() { }
private static Config instance = new Config();
public static Config Instance { get { return Config.instance; } }
private readonly int DefaultExampleInteger = 0xffff;
private readonly double DefaultExampleDouble = 3.14159265358979;
private readonly string DefaultExampleString = "example";
private readonly bool DefaultExampleBoolean = true;
public int ExampleInteger { get; set; }
public double ExampleDouble { get; set; }
public string ExampleString { get; set; }
public bool ExampleBoolean { get; set; }
}
}
using System;
using System.Reflection;
public static class MemberInfoExtension
{
public static bool HasAttribute<T>(this MemberInfo mi)
where T : Attribute
{
Attribute attribute = Attribute.GetCustomAttribute(mi, typeof(T));
return (attribute != null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment