将表单传递的参数反射成类对象

参考资料:http://www.voidcn.com/article/p-psfrqmsx-ex.html

public class AuthModel<T>
{
    public T Instance;   
    public AuthModel(string Fiedls)
    {
        this.Fiedls = Fiedls;
        Instance = Load(Fiedls);
    }

    T Load(string fields)
    {
        string[] arr = fields.Split(',');
        return Instantiation(arr);
    }

    /// <summary>
    /// 转换
    /// </summary>
    T Instantiation(string[] arr)
    {
        T tInstance = (T)Activator.CreateInstance(typeof(T));
        PropertyInfo[] tProperties = tInstance.GetType().GetProperties();

        foreach (string key in arr)
        {
            var kVal = HttpContext.Current.Request.QueryString[key];
            if (kVal == null)
            {
                kVal = HttpContext.Current.Request.Form[key];
            }
            if (kVal != null)
            {
                foreach (var proper in tProperties)
                {
                    if (proper.Name.ToUpper().Equals(key.ToUpper()))
                    {
                        proper.SetValue(tInstance, Convert.ChangeType(kVal, proper.PropertyType), null);
                    }
                }
            }
        }
        return tInstance;
    }
}

使用方法:

//构造函数是传递AdminModel类的属性字段名称
AuthModel<AdminModel> autoModel = new AuthModel<AdminModel>("id,name,truename,password,state,groupid,groupname,agent_id,logourl,gender");
相关文章
相关标签/搜索