C# 遍歷類的屬性並取出值


   最近悟出來一個道理,在這兒分享給大家:學歷代表你的過去,能力代表你的現在,學習代表你的將來。

   十年河東十年河西,莫欺少年窮

   學無止境,精益求精

   今天有點胡思亂想,想遍歷MVC Model的屬性並取值:

   這個方法還是很簡單的,通過反射即可遍歷屬性,我總結的方法如下:

namespace WeiXinApi.CommonCS
{
    public class ForeachClass
    {
        /// <summary>
        /// C#反射遍歷對象屬性
        /// </summary>
        /// <typeparam name="T">對象類型</typeparam>
        /// <param name="model">對象</param>
        public static void ForeachClassProperties<T>(T model)
        {
            Type t = model.GetType();
            PropertyInfo[] PropertyList = t.GetProperties();
            foreach (PropertyInfo item in PropertyList)
            {
                string name = item.Name;
                object value = item.GetValue(model, null);
            }
        }
    }
}

   下面我們來簡單測試下:

    新建Model如下:

 public class AddressInfo
    {
        public int Id { get; set; }
        public string userName { get; set; }
        public string userTel { get; set; }
        public string Addressdetail { get; set; }
        public int isMoren { get; set; }

        public AddressInfo()
        {
            Id = 1;
            userName = "陳卧龍";
            userTel = "1813707015*";
            Addressdetail = "江蘇省蘇州市工業園區國際科技園";
            isMoren = 1;
        }
}

   調用如下:

    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Response.Redirect("/Home/Login");
            AddressInfo model = new AddressInfo();
            ForeachClass.ForeachClassProperties<AddressInfo>(model);
        }
    }

   測試結果如下:

   經過測試,我們可以得到對象的各個屬性及對應的值、

   其實這塊內容輸入C# 反射系列,小弟也是誤打誤撞,撞入了C# 反射,索性每天學一點

   @陳卧龍的博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM