Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12395646
  • 博文数量: 1293
  • 博客积分: 13501
  • 博客等级: 上将
  • 技术积分: 17974
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 18:11
文章分类

全部博文(1293)

文章存档

2019年(1)

2018年(1)

2016年(118)

2015年(257)

2014年(128)

2013年(222)

2012年(229)

2011年(337)

分类: C#/.net

2013-09-05 17:40:44

一、属性的基本概念

1、什么是属性?为什么要使用属性?

    属性提供功能强大的方法以将声明信息与 C# 代码(类型、方法、属性等)相关联。特别在数据库设计中,一个数据库中的各个字段的性质不一样,有的是primary key,有的是key,有的则是普通的字段,通过属性的该表的类中进行字段标识,使用时通过反射出这些属性就可以知道这个字段的信息。

2、属性的两种表现形式

    一种是在公共语言运行时 (CLR) 中定义的属性。
    另一种是可以创建的用于向代码中添加附加信息的自定义属性。此信息可在以后以编程方式检索。

3、属性的使用场合

    属性可以放置在几乎所有的声明中(但特定的属性可能限制在其上有效的声明类型)。

4、属性的使用语法

    在语法上,属性的指定方法为:将括在方括号中的属性名置于其适用的实体声明之前。

二、属性的案例说明

    本案例主要实现自定义属性类DescriptionAttribute,在类CNBAStar及其成员中应用该属性,并在main()中通过反射的方式将这些属性获取。
案例代码:

点击(此处)折叠或打开

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;

  6. namespace CustomAttibute2
  7. {
  8.     class Program
  9.     {
  10.         [Description("I'm class CNBAStar ",ExtraInfo="private")]
  11.         class CNBAStar
  12.         {
  13.             private string mName = "Michael Jordan";

  14.             #region Properties field
  15.             [Description("I'm CNBAStar's attribute Name")]
  16.             public string Name
  17.             {
  18.                 get { return mName; }
  19.                 set { Name = mName; }
  20.             }
  21.             #endregion

  22.             #region Methods field
  23.             [Description("I'm CNBAStar's mothed ShowTime()",ExtraInfo="public")]
  24.             public string ShowTime()
  25.             { return mName + " is most famous basketball player of the world!"; }

  26.             [method: Description("I'm CNBAStar's mothed ShowTime2()")]
  27.             public string ShowTime2()
  28.             { return "Kobe Brynt is so so."; }

  29.             [return: Description("Just mark the return value of showTime3() ")]
  30.             public string ShowTime3()
  31.             { return "Lebron James is so so."; }
  32.             #endregion
  33.         }

  34.         static void Main(string[] args)
  35.         {
  36.             /* 反射出CNBAStar class中携带信息的方法 */
  37.             Object[] attrs = typeof(CNBAStar).GetCustomAttributes(true);
  38.             foreach (Object obj in attrs)
  39.             {
  40.                 if (obj is DescriptionAttribute)
  41.                 {
  42.                     Console.WriteLine((obj as DescriptionAttribute).MData);
  43.                     Console.WriteLine("===================================================");
  44.                 }
  45.             }

  46.             /* 反射出CNBAStar class中相关属性、方法所携带信息的方法:
  47.              * 先获取class.members,再取type.GetCustomAttributes() */
  48.             MemberInfo[] members = typeof(CNBAStar).GetMembers();
  49.             foreach (MemberInfo member in members)
  50.             { ParseAttributes(member); }

  51.             Console.ReadKey();
  52.         }


  53.         /** *************************************************************************************************
  54.          * DESC : 将class的members所携带的信息一 一进行反射
  55.          * ARGC :
  56.          * @type: member's all infomation.
  57.          * RET:
  58.          *---------------------------------------------------------------------------------------------------
  59.         ****************************************************************************************************/
  60.         static void ParseAttributes(MemberInfo type)
  61.         {
  62.             object[] attributes = type.GetCustomAttributes(true);
  63.             Console.WriteLine("{0} {1}'s attributes:", type.MemberType.ToString(), type.Name);

  64.             if (attributes.Length != 0)
  65.             {
  66.                 foreach (object attribute in attributes)
  67.                 {
  68.                     Console.WriteLine(" Attribute =[{0}]", attribute.ToString());
  69.                     DescriptionAttribute da = attribute as DescriptionAttribute;
  70.                     if (da != null)
  71.                     {
  72.                         Console.WriteLine(".Description = {0}",da.MData);
  73.                         if (da.ExtraInfo != "")
  74.                             Console.WriteLine(".ExtraInfo = {0}", da.ExtraInfo);
  75.                         else
  76.                             Console.WriteLine(".ExtraInfo=\"\"");
  77.                     }
  78.                     Console.WriteLine();
  79.                 }
  80.             }
  81.             else
  82.                 Console.WriteLine(" {0} has no attributes\n", type.Name);
  83.         }


  84.         [AttributeUsage(AttributeTargets.All)]
  85.         public class DescriptionAttribute : Attribute
  86.         {
  87.             private string mData;
  88.             private string mExtraInfo;
  89.             private string mThirdInfo;

  90.             public DescriptionAttribute(string data)
  91.             {
  92.                 mData = data;
  93.                 mExtraInfo = "";
  94.                 mThirdInfo = "";
  95.             }

  96.             public string MData
  97.             {
  98.                 get { return mData; }
  99.             }

  100.             /* Extra infomation */
  101.             public string ExtraInfo
  102.             {
  103.                 get { return mExtraInfo; }
  104.                 set { mExtraInfo = value; ; }
  105.             }

  106.             public string ThirdInfo
  107.             {
  108.                 get { return mThirdInfo; }
  109.                 set { mThirdInfo = value; ; }
  110.             }
  111.         }

  112.     }
  113. }


image

图2-1

    上图是使用程序中使用了[Description]属性的类、方法、Property被反射出的属性信息。

三、定位参数与命令参数

    自定义属性类中构造函数的参数称之为定位参数(即本例的data),任何公共读写字段或属性都是命令参数。两类参数的区别:

1、定位参数是构造函数带的参数,必须填写,下面是典型的报错:

  1. [Description]
  2. private string mName = "Michael Jordan";

错误    1    “CustomAttibute2.Program.DescriptionAttribute”不包含采用“0”参数的构造函数    

2、命令参数能选择性填写,并且顺序不要求。
    本例中的下面两种写法都是正确的

顺序一:

  1. [Description("I'm CNBAStar's mothed ShowTime()",ExtraInfo="public",ThirdInfo=="3#")]
  2. public string ShowTime()

顺序二:

  1. [Description("I'm CNBAStar's mothed ShowTime()",ThirdInfo=="3#",ExtraInfo="public")]
  2. public string ShowTime()

四、消除属性目标的歧义性

  1. [Description("I'm CNBAStar's mothed ShowTime()",ExtraInfo="public")]
  2. public string ShowTime()
  3. { return mName + " is most famous basketball player of the world!"; }

    上面代码中,虽然.NET内部将这个Description习惯归于ShowTime()方法,但表面上看这样的写法仍然让人容易误解:这个属性到底是属性方法ShowTime()还是属性它的返回值?

    为了解决这种歧义,在属性中添加了method和return参数作为区分,如下:

    属性标识方法ShowTime2()

  1. [method: Description("I'm CNBAStar's mothed ShowTime2()")]
  2. public string ShowTime2()
  3. { return "Kobe Brynt is so so."; }

    属性标识返回值

  1. [return: Description("Just mark the return value of showTime3() ")]
  2. public string ShowTime3()
  3. { return "Lebron James is so so."; }



参考文献:

1、

Using Custom Attributes in C# - By David Clegg

2、 

消除属性目标的歧义性

3、

SQLServer:如何使用C#自定义属性

4、

如何在C#中自定义属性

阅读(6682) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~