如何自定义特性并解析它们

        如何自定义特性并解析它们

                               电子科技大学软件学院03级02班 周银辉

         特性(Attribute),使得我们可以将一些自定义信息附加到程序实体上,这非常有用,比如我们可以利用它来加密函数库,记录其它一些重要信息等。

        1,如何定义一个我们所需要的特性:
               1),特性实际上和普通的类一样,只不过它必须继承于Attribute类。
               2),我们适用AttributeUsage特性来限定自定义特性的使用范围。
        比如我们创建一个用于给类加密的密码特性:
        
///   <summary>
    
///  自定义密码特性,该特性只可应用于类
    
///   </summary>
    [AttributeUsage(AttributeTargets.Class)]
    
public   class  PasswordAttribute : Attribute
    {
        
string  psw;

        
public   string  Psw
        {
            
get
            {
                
return  psw;
            }
            
set
            {
                psw 
=  value;
            }
        }

        
public  PasswordAttribute( string  psw)
        {
            
this .psw  =  psw;
        }
    }

    以后我们就可以像使用其它特性一样将我们的密码特性作用于其它类上了。
    比如:
     ///   <summary>
    
///  测试类,该类有一个密码特性
    
///   </summary>
    [Password( " 123 " )]
    
public   class  TestClass
    {
       
    }


    
    2,如何解析自定义的特性:
    我们将TestClass赋予了一个密码“123”,我们如何解析出这个密码呢?
    很简单,这需要了解一个名为CustomAttributeData的类,它为自定义特性提供反射访问。
    比如:
        ///   <summary>
        
///  获取指定类型的密码特性
        
///   </summary>
        
///   <param name="type"> 类型 </param>
        
///   <returns> 密码 </returns>
         public   static   string  GetPassword(Type type)
        {

            
// 扫描指定类型的所有自定义特性
             foreach  (CustomAttributeData data  in  CustomAttributeData.GetCustomAttributes(type))
            {
                
// 如果是密码特性
                 if  (data.Constructor.DeclaringType.Equals( typeof (PasswordAttribute)))
                {
                    
// 返回密码特性的第一个参数,也就是密码
                     if  (data.ConstructorArguments.Count  >   0 )
                    {
                        
return  data.ConstructorArguments[ 0 ].Value.ToString();
                    }
                }
            }

            
return   string .Empty;
        }

 

其它更复杂的操作可以参考MSDN,以下是上面示例的完整代码:

ContractedBlock.gif ExpandedBlockStart.gif 示例代码
 1None.gifusing System;
 2None.gifusing System.Collections.Generic;
 3None.gifusing System.Text;
 4None.gifusing System.Reflection;
 5None.gif
 6None.gif
 7None.gifnamespace AttributeTest
 8ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 9InBlock.gif    class Program
10ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
11InBlock.gif        static void Main(string[] args)
12ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
13InBlock.gif            string psw = PasswordParser.GetPassword(typeof(TestClass));
14InBlock.gif
15InBlock.gif            Console.WriteLine("password is:{0}", psw);
16ExpandedSubBlockEnd.gif        }

17ExpandedSubBlockEnd.gif    }

18InBlock.gif
19InBlock.gif
20ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
21InBlock.gif    /// 自定义密码特性,该特性只可应用于类
22ExpandedSubBlockEnd.gif    /// </summary>

23InBlock.gif    [AttributeUsage(AttributeTargets.Class)]
24InBlock.gif    public class PasswordAttribute : Attribute
25ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
26InBlock.gif        string psw;
27InBlock.gif
28InBlock.gif        public string Psw
29ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
30InBlock.gif            get
31ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
32InBlock.gif                return psw;
33ExpandedSubBlockEnd.gif            }

34InBlock.gif            set
35ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
36InBlock.gif                psw = value;
37ExpandedSubBlockEnd.gif            }

38ExpandedSubBlockEnd.gif        }

39InBlock.gif
40InBlock.gif        public PasswordAttribute(string psw)
41ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
42InBlock.gif            this.psw = psw;
43ExpandedSubBlockEnd.gif        }

44ExpandedSubBlockEnd.gif    }

45InBlock.gif
46InBlock.gif
47ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
48InBlock.gif    /// 测试类,该类有一个密码特性
49ExpandedSubBlockEnd.gif    /// </summary>

50InBlock.gif    [Password("123")]
51InBlock.gif    public class TestClass
52ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
53InBlock.gif       
54ExpandedSubBlockEnd.gif    }

55InBlock.gif
56InBlock.gif
57ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
58InBlock.gif    /// 密码特性解析器
59ExpandedSubBlockEnd.gif    /// </summary>

60InBlock.gif    public class PasswordParser
61ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
62ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
63InBlock.gif        /// 获取指定类型的密码特性
64InBlock.gif        /// </summary>
65InBlock.gif        /// <param name="type">类型</param>
66ExpandedSubBlockEnd.gif        /// <returns>密码</returns>

67InBlock.gif        public static string GetPassword(Type type)
68ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
69InBlock.gif
70InBlock.gif            //扫描指定类型的所有自定义特性
71InBlock.gif            foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(type))
72ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
73InBlock.gif                //如果是密码特性
74InBlock.gif                if (data.Constructor.DeclaringType.Equals(typeof(PasswordAttribute)))
75ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
76InBlock.gif                    //返回密码特性的第一个参数,也就是密码
77InBlock.gif                    if (data.ConstructorArguments.Count > 0)
78ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
79InBlock.gif                        return data.ConstructorArguments[0].Value.ToString();
80ExpandedSubBlockEnd.gif                    }

81ExpandedSubBlockEnd.gif                }

82ExpandedSubBlockEnd.gif            }

83InBlock.gif
84InBlock.gif            return string.Empty;
85ExpandedSubBlockEnd.gif        }

86ExpandedSubBlockEnd.gif    }

87ExpandedBlockEnd.gif}

88None.gif


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值