using System;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
namespace CodeCompress.ShortReflAttr
{
public abstract class AbstractModel : ContextBoundObject
{
public AbstractModel()
{
}
public AbstractModel(object src)
{
CopyByRefl(src, this);
}
protected void OnPropertyChanged(string propertyName)
{
IEnumerable var = ValidateBase(propertyName);
// このあといろいろやる
}
protected IEnumerable ValidateBase(string propertyName)
{
string propValidaterName = "SetPropValidate_" + propertyName;
MethodInfo mi = this.GetType().GetMethod(propValidaterName, BindingFlags.NonPublic | BindingFlags.Instance);
if (mi != null)
{
List<string> messages = new List<string>();
object[] methodParams = new object[1];
methodParams[0] = messages;
mi.Invoke(this, methodParams);
if (messages.Count > 0)
{
return messages;
}
else
{
return null;
}
}
else
{
return null;
}
}
/// <summary>
/// リフレクションを使ったコピー
/// このコピーのレギュレーションは、すべての「プロパティ」同士のコピー
/// </summary>
/// <param name="src">コピー元</param>
/// <param name="dst">コピー先</param>
protected void CopyByRefl(object src, object dst)
{
PropertyInfo[] piArray = src.GetType().GetProperties();
foreach (PropertyInfo pi in piArray)
{
pi.SetValue(dst, pi.GetValue(src, null), null);
}
}
/// <summary>
/// プロパティの値保存用のコンテナ
/// </summary>
protected Dictionary<string, object> _propValues = new Dictionary<string, object>();
protected void SetPropValue(string propertyName, object val, object src)
{
object o = GetPropValue(propertyName, src);
if (o != null)
{
if (o.Equals(val))
{
return;
}
}
else
{
if (src == null)
{
return;
}
}
_propValues[propertyName] = val;
this.OnPropertyChanged(propertyName);
}
protected object GetPropValue(string propertyName, object src)
{
if (_propValues.ContainsKey(propertyName))
{
return _propValues[propertyName];
}
else
{
Type t = src.GetType().GetProperty(propertyName).PropertyType;
if (t == typeof(string))
{
return null;
}
else if (t == typeof(int))
{
return 0;
}
else if (t == typeof(decimal))
{
return 0m;
}
else if (t == typeof(bool))
{
return false;
}
else if (t == typeof(DateTime))
{
return DateTime.MinValue;
}
return null;
}
}
}
}