[聚合文章] 设置Nullable<T>类型对象的值为default(T)

c# 2014-11-11 3 阅读
public T CreateDefault()
{
    T item = new T();

    foreach (var p in typeof(T).GetProperties())
    {
        Type colType = p.PropertyType;

        if (colType == typeof(Nullable<DateTime>))
        {
            p.SetValue(item, DateTime.Now, null);
        }
        else if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            var t = Nullable.GetUnderlyingType(colType);
            p.SetValue(item, Activator.CreateInstance(t), null);
        }
    }

    return item;
}

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。