Last active
August 29, 2015 14:23
-
-
Save anzfactory/cfe63068ef3599fd2ff6 to your computer and use it in GitHub Desktop.
オートマチックにデータクラスへデータをセットするやつ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace App.Data { | |
// データクラス基底 | |
abstract public class AbstractData | |
{ | |
public void Setup(Dictionary<string, object>data) | |
{ | |
// フィールド全部情報取得 | |
var fields = GetType().GetFields(); | |
foreach (var fieldInfo in fields) { | |
// フィールドに設定されている属性を取得する | |
ColAttribute attribute = | |
System.Attribute.GetCustomAttribute( | |
fieldInfo, | |
typeof(ColAttribute) | |
) as ColAttribute; | |
// 取得した属性からカラム名をとってきて、それでデータ取得 | |
var val = data[attribute.Name]; | |
// 特殊なタイプか判定する | |
if (attribute.HasConverter) { | |
fieldInfo.SetValue( | |
this, | |
((IColConverter)this).Convert(val, attribute.Name) // 特殊な変換処理をinterfaceを介してサブクラスに投げる | |
); | |
} else { | |
fieldInfo.SetValue( | |
this, | |
System.Convert.ChangeType(val, fieldInfo.FieldType) | |
); | |
} | |
} | |
} | |
} | |
// 特殊な変換処理用のインターフェース(delegateでもいいかも) | |
public interface IColConverter | |
{ | |
object Convert(object val, string colName); | |
} | |
// 属性(こっちは例にあげたまま) | |
[AttributeUsage(AttributeTargets.Field)] | |
public class ColAttribute : Attribute | |
{ | |
private String name; // カラム名 | |
public String Name { get { return this.name; } } | |
private bool hasConverter; | |
public bool HasConverter { get { return this.hasConverter; } } | |
public ColAttribute(string name) : this(name, false) | |
{ | |
} | |
public ColAttribute(string name, bool has) | |
{ | |
this.name = name; | |
this.hasConverter = has; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment