static Dictionary<Type, List<PropertyInfo>> DatePropsCache =
new Dictionary<Type, List<PropertyInfo>>();
/// <summary>
/// 掃瞄資料物件的DateTime型別屬性,將DateTimeKind.Unspecified改為DateTimeKind.Local
/// </summary>
/// <param name="entity">資料</param>
public static void FixUnspecifiedDateKind(object entity)
{
if (entity != null)
{
Type type = entity.GetType();
//以Reflection找出所有DateTime或DateTime?型別屬性
//每個型別只要做一次,使用Cache省去多餘運算
List<PropertyInfo> dateProps = DatePropsCache.ContainsKey(type) ?
DatePropsCache[type] : null;
if (dateProps == null)
{
lock (DatePropsCache)
{
//找出所有DateTime及DateTime?屬性的PropertyInfo
DatePropsCache[type] = type.GetProperties()
.Where(o =>
o.PropertyType == typeof(DateTime) ||
o.PropertyType == typeof(DateTime?)
).ToList();
}
dateProps = DatePropsCache[type];
}
foreach (var dateProp in dateProps)
{
//取得目前屬性值
object curVal = dateProp.GetValue(entity);
if (curVal != null)
{
DateTime dt = dateProp.PropertyType.IsGenericType ?
((DateTime?)curVal).Value : (DateTime)curVal;
//若DateTimeKind為Unspecified,改設定為Local
if (dt.Kind == DateTimeKind.Unspecified)
dateProp.SetValue(entity,
DateTime.SpecifyKind(dt, DateTimeKind.Local));
}
}
}
}