C# 反射和特性查重的詳細介紹

來源:互聯網
上載者:User

反射和特性

 .net framework提供的反射和特性技術,可以用來檢查資料重複性,以決定是否向資料庫表中寫入某條資料。  

需求

  某個實體向資料庫寫入一條資料時,很多時候,需要檢查這條資料是不是一條重複資料,比如建立的人員,假定ID號碼不能重複,此時建立的這個人員ID號與人員表中的一條或多條重複了,此時需要給出提示或採取其他手段,比如更新,或刪除等。

方法

  在這種需求情境下,可以利用.net framework提供的特性與反射技術,解決此類需求。具體過程,

  其次,在實體類中引用剛寫好的屬性類別構造出其唯一標識(一個或多個屬性群組合);
  
  最後,檢查資料重複性時,運用Attribute提供的方法,擷取每個實體類的唯一性識別屬性(一個或多個)。
  
  Attribute[] GetCustomAttributes(modeltype, inherit);

KeyFieldAttribute 屬性類別

     public class KeyFieldAttribute:Attribute     {        private static List<string> keyfields = new List<string>();             /// <summary>        /// 構造關鍵屬性        /// </summary>        /// <param name="fields"></param>        public KeyFieldAttribute(params string[] fields)        {            foreach (string kf in fields)            {                if (!keyfields.Contains(kf))                    keyfields.Add(kf);            }        }        public static List<string> KeyFields        {            get { return keyfields; }        }    }

實體類Model

[KeyField("ID")]public class Person{  public int ID {get;set;} //人員ID  public string Name {get;set;}//人員名稱  public DateTime BirthDate {get;set;} //出生年月日}    [KeyField("RoleGroupID","RoleCode")]    public class Role    {        public int RoleGroupID { get; set; } //角色群組別ID        public string RoleCode { get; set; } //角色編號        public string RoleName { get; set; }//角色名稱    }

  注意特性擴充類,此處是KeyFieldAttribute中的尾碼Attribute是可以省略的,因此KeyField是簡寫,相當於KeyFieldAttribute。

運用屬性類別:

            KeyFieldAttribute.GetCustomAttributes(typeof(Person), true);            List<string> fields = KeyFieldAttribute.KeyFields; //擷取到Person實體的唯一識別屬性ID            KeyFieldAttribute.GetCustomAttributes(typeof(Role), true);                        var fields = KeyFieldAttribute.KeyFields;//Role實體唯一屬性,2個屬性群組合:RoleGroupID,RoleCode

  利用特性返回的關鍵屬性群組合,在資料庫中查詢資料,如果能查到至少一條記錄,則按照一定的邏輯處理; 如果不能,則可以直接寫入新資料。Attribute類中提供的方法說明:

/// <summary>/// 檢索應用於類型的成員的自訂特性的數組。/// </summary>/// <param name="modeltype">要搜尋的自訂特性的類型</param>///<param name="inherit">是否搜尋成員的祖先</param>/// <returns>自訂特性的數組</returns>Attribute[] GetCustomAttributes(modeltype, inherit);

以上就是C# 反射和特性查重的詳細介紹的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.