.Net之自訂特性

來源:互聯網
上載者:User

標籤:資料   and   問題   pre   rac   line   cat   解決   final   

剛接觸C#的朋友常常容易把屬性(Property)跟特性(Attribute)搞混,其實這是兩種不同的東西

屬性指的類中封裝的資料欄位;而特性是對類、欄位、方法和屬性等元素標註的聲明性資訊

如下代碼(Id、Name為User的屬性,[DbKey]為Id的特性)

/// <summary>/// 使用者資訊/// </summary>public class User{    [DbKey]    public string Id { get; set; }    public string Name { get; set; }}

特性分預定義特性和自訂特性,本節重點講述自訂特性

自訂特性有什麼用?能解決什麼問題?

直接上代碼

namespace CustomerAttribute{    /// <summary>    /// 自訂特性    /// </summary>    public class DbKey : Attribute    {        public string Description { get; set; }        public DbKey()        {        }        public DbKey(string description)        {            this.Description = description;        }    }}
namespace CustomerAttribute{    /// <summary>    /// 使用者資訊    /// </summary>    public class User    {        [DbKey]        public string Id { get; set; }        public string Name { get; set; }    }    /// <summary>    /// 使用者角色    /// </summary>    public class UserRole    {        [DbKey("使用者ID")]        public string UserId { get; set; }        [DbKey("角色ID")]        public string RoleId { get; set; }    }}
namespace CustomerAttribute{    class Program    {        /// <summary>        /// 擷取資料庫主鍵欄位        /// </summary>        /// <typeparam name="T"></typeparam>        /// <returns></returns>        private static IEnumerable<PropertyInfo> getDbKeyFields<T>()        {            // 擷取當前類中的公用欄位            var fields = typeof(T).GetProperties();            // 尋找有DbKey特性的欄位            var keyFields = fields.Where(field => (DbKey)Attribute.GetCustomAttribute(field, typeof(DbKey)) != null);            return keyFields;        }        private static string getDescription(PropertyInfo field)        {            string result = string.Empty;            var dbKey = (DbKey)Attribute.GetCustomAttribute(field, typeof(DbKey));            if (dbKey != null) result = dbKey.Description;            return result;        }        static void Main(string[] args)        {            try            {                var userKeyFields = getDbKeyFields<User>();                Console.WriteLine("User表的主鍵為:" + string.Join(",", userKeyFields.Select(field => field.Name)));                var userRoleKeyFields = getDbKeyFields<UserRole>();                Console.WriteLine("UserRole表的主鍵為:" + string.Join(",", userRoleKeyFields.Select(field => field.Name)));                foreach (PropertyInfo field in userRoleKeyFields)                {                    string description = getDescription(field);                    Console.WriteLine(string.Format("{0}欄位的描述資訊為:{1}", field.Name, description));                }            }            catch (Exception ex)            {                Console.WriteLine(ex);            }            finally            {                Console.ReadLine();            }        }    }}
View Code

從上邊代碼可以看出來,自訂特性本身也是類,繼承自Attribute類,當我們對類、方法、屬性等元素進行特性標註的時候,即可在程式中擷取相關特性資訊

在entity framework中我們通常會對類、欄位進行特性標註,當欄位被標上[Key]時,程式即可從實體中找出主鍵欄位,實現到資料庫表間的映射,然後產生表主鍵

上邊是一個簡單樣本,我們可以通過自訂[DbKey]特性,標註在實體欄位上,然後通過程式自動找出主鍵欄位,同樣也可以標註其他描述性資訊等

.Net之自訂特性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.