C#獲取實體類字段信息PropertyInfo,字段名稱,字段值,字段屬性標籤

引用空間:
System.Reflection.PropertyInfo

 AnUser anUser = new AnUser();
            anUser.Id = "514f275979f64531b7fbbb2f89c8af49";
            anUser.UserNo = "5566110";
            PropertyInfo[] props = typeof(AnUser).GetProperties();//實體的字段列表
            foreach (var item in props)
            {
                //item.Name 獲取字段名稱
                if (item.Name == "Id")
                {
                   string id =  item.GetValue(anUser) as string;//獲取字段值
                }
                var kkkk = item.Attributes;
                var kkkk2 = item.CustomAttributes;//自定義的屬性標籤
           
                //獲取字段是否有[Key]屬性標籤
                bool isHave = kkkk2.Any(x => x.AttributeType == typeof(System.ComponentModel.DataAnnotations.KeyAttribute));
            }
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ayy.Models
{
    /// <summary>
    /// 用戶
    /// </summary>
    [Table("AnUser")]
    public class AnUser
    { 
 
	    /// <summary>
        /// guid主鍵
        /// </summary>
        [Key]
        public string Id { set; get; }
		
        /// <summary>
        /// 工號
        /// </summary>
        public string UserNo { get; set; }
 
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章