Mirror site is read only www.netnr.com
netnr/ RequesToModel.cs 2018-09-26 13:08
反射参数为实体
/// <summary>
/// 反射参数为实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="request"></param>
/// <returns></returns>
public static T RequesToModel<T>(this T model, HttpRequest request = null)
{
    if (request == null)
    {
        request = HttpContext.Current.Request;
    }
    PropertyInfo[] properties = model.GetType().GetProperties();
    for (int i = 0; i < properties.Length; i++)
    {
        PropertyInfo pi = properties[i];
        object value = request[pi.Name];
        Type type = pi.PropertyType;
        if (pi.PropertyType.FullName.Contains("System.Nullable"))
        {
            type = Type.GetType("System." + pi.PropertyType.FullName.Split(',')[0].Split('.')[2]);
        }
        try
        {
            value = Convert.ChangeType(value, type);
            pi.SetValue(model, value, null);
        }
        catch (Exception)
        {
        }
    }
    return model;
}