C# 反射與特性查重的詳細介紹
反射與特性
.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; } } }
KeyFieldAttribute 特性類別
[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.GetCustomAttributes(typeof(Person), true); List<string> fields = KeyFieldAttribute.KeyFields; //获取到Person实体的唯一标识属性ID KeyFieldAttribute.GetCustomAttributes(typeof(Role), true); var fields = KeyFieldAttribute.KeyFields;//Role实体唯一属性,2个属性组合:RoleGroupID,RoleCode
運用特性類別:
/// <summary>/// 检索应用于类型的成员的自定义特性的数组。 /// </summary>/// <param name="modeltype">要搜索的自定义特性的类型</param> ///<param name="inherit">是否搜索成员的祖先</param> /// <returns>自定义特性的数组</returns>Attribute[] GetCustomAttributes(modeltype, inherit);
利用特性傳回的關鍵屬性組合,在資料庫中查詢數據,如果能查到至少一筆記錄,則按照一定的邏輯處理; 如果不能,則可以直接寫入新資料。 Attribute類別中提供的方法說明:
rrreee

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

使用 C# 的 Active Directory 指南。在這裡,我們討論 Active Directory 在 C# 中的介紹和工作原理以及語法和範例。

多線程和異步的區別在於,多線程同時執行多個線程,而異步在不阻塞當前線程的情況下執行操作。多線程用於計算密集型任務,而異步用於用戶交互操作。多線程的優勢是提高計算性能,異步的優勢是不阻塞 UI 線程。選擇多線程還是異步取決於任務性質:計算密集型任務使用多線程,與外部資源交互且需要保持 UI 響應的任務使用異步。
