使用反射和Attribute动态显示代码中的注释内容

  

  反射和Attribute是.NET的两种技术,可以应用在很多的地方。

  反射可以反射类中的属性,方法,实现动态调用,也经常在三层工厂中使用,反射接口的实现。

  Attribute,个人理解,就是一个特性,可以添加在任何自定义类型上面,然后添加一些注释,也是很有用的。

  本篇就示例讲解一个他们的结合使用:使用反射和Attribute动态显示代码中的注释内容。其中也杂合它一些其他的内容,一个是前几天写的一个C#的加密解密算法,包括Silverlight的MD5算法。还有就是一个商品规格的计算方法,比如给出需要购买的总量,然后计算每种规格需要购买的数量,和总的花费。

  结果如下图

使用反射和Attribute动态显示代码中的注释内容

 

 

  代码如下

  

 

代码
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> using System;
using System.Collections.Generic;
using System.Linq;
using System.
Text ;
using System.Web.Security;
using System.Reflection;

namespace ConsoleApplication1
{
    
[ AttributeUsage(AttributeTargets.Class) ]
    class CodeReviewAttribute : System.Attribute
    {
        private string _reviewer;

        
public  string Reviewer
        {
            get { 
return  _reviewer; }
        }
        private string _date;

        
public  string Date
        {
            get { 
return  _date; }
        }
        private string _comment;

        
public  string Comment
        {
            get { 
return  _comment; }
            
set  { _comment  =  value; }
        }
        
public  CodeReviewAttribute(string reviewer, string date)
        {
            this._reviewer 
=  reviewer;
            this._date 
=  date;
        }
    }
    
[ CodeReview("swb", "2009-9-9", Comment = "代码不好") ]
    class MyClass
    {
    }
    
[ AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field) ]
    class NoteAttribute : System.Attribute
    {
        private string _name;

        
public  string Name
        {
            get { 
return  _name; }
        }
        
public  NoteAttribute(string name)
        {
            this._name 
=  name;
        }
    }

    enum 
Log
    {
        
[ Note("添加 用户") ]
        AddUser,
        
[ Note("修改 用户") ]
        ModifyUser
    }
    class EnumDescription
    {
        
public  static string Parse( Log  type)
        {
            FieldInfo fields 
=  type.GetType().GetField(type.ToString());
            object
[]  objs  =  fields.GetCustomAttributes(true);
            
return  ((NoteAttribute)objs [ 0 ] ).Name;
        }
    }
    
public  interface IChinese
    {
        string Speak();
    }
    
public  class CNSpeaker : IChinese
    {
        #region Chinese Members

        
public  string Speak()
        {
            
return  "Chinese";
        }

        #endregion
    }
    
public  interface IEnglish
    {
        string Speak();
    }
    
public  class ENSpeaker : IEnglish
    {
        #region English Members

        string IEnglish.Speak()
        {
            
return  "English";
        }

        #endregion
    }
    class Program
    {
        static void Main(string
[]  args)
        {
            CNSpeaker cn 
=  new CNSpeaker();
            Console.WriteLine(cn.Speak());
            IEnglish en 
=  new ENSpeaker();
            Console.WriteLine(en.Speak());
            Console.WriteLine("
-- -------------------");
            string  str   =  " 123 ";
            Console.WriteLine(string.Format("
123  encrypt result: { 0 }", WebMD5Provider.WebFormMD5Encrypt( str )));
            Console.WriteLine("
-- -------------------");
            MD5CryptoServiceProvider md5Provider  =  new MD5CryptoServiceProvider();
            byte
[]  encryptedBytes  =  md5Provider.ComputeHash(Encoding.UTF8.GetBytes( str ));
            StringBuilder sb 
=  new StringBuilder();
            
for  ( int  i  =   0 ; i  <  encryptedBytes.Length; i ++ )
            {
                sb.AppendFormat("{
0 :x2}", encryptedBytes [ i ] );
            }

            Console.WriteLine(string.Format("
123  encrypt result: { 0 }", sb.ToString()));
            Console.WriteLine("
-- -------------------");

            System.Reflection.MemberInfo info 
=  typeof(MyClass);
            CodeReviewAttribute att 
=  (CodeReviewAttribute)Attribute.GetCustomAttribute(info, typeof(CodeReviewAttribute));
            
if  (att  !=   null )
            {
                Console.WriteLine("MyClass 代码监察人:{
0 }", att.Reviewer);
                Console.WriteLine("MyClass 检查时间:{
0 }", att.Date);
                Console.WriteLine("MyClass 备注:{
0 }", att.Comment);
            }
            Console.WriteLine("
-- -------------------");
             Log   log   =   Log .AddUser;


            Console.WriteLine(string.Format ("Enum 
Log  的 AddUser 的注释是: { 0 }",EnumDescription.Parse( log )));

            Console.WriteLine("
-- -------------------");
            Int64? bbb  =   0 ;
            
int ? aaa  =   0 ;
            Console.WriteLine("
-- -------------------");

            
decimal  area  =   110 ;
            Console.WriteLine("你的土地面积是:{
0 }", area);
            
decimal  amount  =  10m;
            Console.WriteLine("你的每亩用量是是:{
0 }", amount );
            
decimal  budget  =   0 ;

            List
< pkgspec >  pkgs  =  new List < pkgspec > ();
            pkgs.
Add (new pkgspec() { amount  =   200 , price  =   180 , id  =   2  });
            pkgs.
Add (new pkgspec() { amount  =   100 , price  =   100 , id  =   1  });

            pkgs.
Add (new pkgspec() { amount  =   250 , price  =   250 , id  =   3  });

            pkgs.Sort(new Comparison
< pkgspec > (compareDesc));

            
//  pkgs.Sort(new Comparison < pkgspec > (compareAsc));

            
decimal  totalAmount  =  area  *  amount;
            Console.WriteLine("你的总共用量是:{
0 }", totalAmount);
            
int  num  =   0 ;

            List
< pkgselect >   select   =  new List < pkgselect > ();

            foreach (pkgspec pkg 
in  pkgs)
            {
                
if  (totalAmount  %  pkg.amount  ==  totalAmount)
                {
                    num 
= 1 ;
                    budget 
+=  num  *  pkg.price;
                    
select . Add (new pkgselect() { id  =  pkg.id, num  =  num, price = pkg.price  });
                    
break ;
                }
                
else   if  (totalAmount  %  pkg.amount  ==   0 )
                {
                    num 
=  ( int )(totalAmount  /  pkg.amount);
                    budget 
+=  num  *  pkg.price;
                    
select . Add (new pkgselect() { id  =  pkg.id, num  =  ( int )(totalAmount  /  pkg.amount) , price = pkg.price });
                    
break ;
                }
                
else
                {
                    num 
=  ( int )(totalAmount  /  pkg.amount);
                    budget 
+=  num  *  pkg.price;
                    
select . Add (new pkgselect() { id  =  pkg.id, num  =  num , price = pkg.price });
                    totalAmount 
=  totalAmount  -  num  *  pkg.amount;
                    
continue ;
                }
            }

            foreach (pkgselect s 
in   select )
            {
                Console.WriteLine("你需要购买的包装编号是:{
0 }, 数量是 { 1 } 个 , 单价是 { 2 }", s.id, s.num, s.price);
            }
            Console.WriteLine("你购买的总价是: {
0 }", budget);

            Console.ReadLine();
        }
        private static 
int  compareAsc(pkgspec pkg1, pkgspec pkg2)
        {
            
if  (pkg1.amount  >  pkg2.amount)
                
return   1 ;
            
if  (pkg1.amount  <  pkg2.amount)
                
return   - 1 ;
            
else
                
return   0 ;
        }
        private static 
int  compareDesc(pkgspec pkg1, pkgspec pkg2)
        {
            
if  (pkg1.amount  <  pkg2.amount)
                
return   1 ;
            
if  (pkg1.amount  >  pkg2.amount)
                
return   - 1 ;
            
else
                
return   0 ;
        }
    }
    
///   < summary >
    
///  选中的包装
    
///   </ summary >
    class pkgselect
    {
        
///   < summary >
        
///  选中ID
        
///   </ summary >
        
public   int  id;
        
///   < summary >
        
///  购买数量
        
///   </ summary >
        
public   int  num;
        
///   < summary >
        
///  单价
        
///   </ summary >
        
public   decimal  price;
    }
    
///   < summary >
    
///  包装类型
    
///   </ summary >
    class pkgspec : IComparable
< pkgspec >
    {
        
///   < summary >
        
///  编号
        
///   </ summary >
        
public   int  id;
        
///   < summary >
        
///  包装量
        
///   </ summary >
        
public   decimal  amount;
        
///   < summary >
        
///  价格
        
///   </ summary >
        
public   decimal  price;

        #region IComparable
< pkgspec >  Members

        
public   int  CompareTo(pkgspec other)
        {
            
if  (this.amount  >  other.amount)
                
return   1 ;
            
if  (this.amount  ==  other.amount)
                
return   0 ;
            
else
                
return   - 1 ;
        }

        #endregion
    }
}

 

 

代码
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> using System;
using System.Collections.Generic;
using System.Linq;
using System.
Text ;
using System.Web.Security;
using System.Security.Cryptography;
using System.IO;

namespace ConsoleApplication1
{
    
///   < summary >
    
///  字符串加解密工具类
    
///   </ summary >
    
public  static class EncryptUtility
    {
        #region WinForm 的MD5和SHA1哈希,使得和System.Web.Security.FormsAuthentication的结果一致

        
public  static string WinFormMD5Encrypt(string data)
        {
            MD5CryptoServiceProvider md5 
=  new MD5CryptoServiceProvider();
            byte
[]  encryptedBytes  =  md5.ComputeHash(Encoding. ASCII .GetBytes(data));
            StringBuilder sb 
=  new StringBuilder();

            
for  ( int  i  =   0 ; i  <  encryptedBytes.Length; i ++ )
            {
                sb.AppendFormat("{
0 :x2}", encryptedBytes [ i ] );
            }
            
return  sb.ToString().ToUpper();
        }
        
public  static string WinFormSHA1Encrypt(string data)
        {
            SHA1CryptoServiceProvider md5 
=  new SHA1CryptoServiceProvider();
            byte
[]  encryptedBytes  =  md5.ComputeHash(Encoding. ASCII .GetBytes(data));
            StringBuilder sb 
=  new StringBuilder();

            
for  ( int  i  =   0 ; i  <  encryptedBytes.Length; i ++ )
            {
                sb.AppendFormat("{
0 :x2}", encryptedBytes [ i ] );
            }
            
return  sb.ToString().ToUpper();
        }
        #endregion

        #region WebForm中的 MD5 和 SHA1 哈希

        
///   < summary >
        
///  返回MD5哈希结果
        
///   </ summary >
        
///   < param name = "password" ></ param >
        
///   < returns ></ returns >
        
public  static string WebFormMD5Encrypt(string data)
        {
            
if  (string.IsNullOrEmpty(data))
                throw new Exception("加密字符串不能为空");
            
return  FormsAuthentication.HashPasswordForStoringInConfigFile(data, "md5");
        }
        
///   < summary >
        
///  返回SHA1哈希结果
        
///   </ summary >
        
///   < param name = "password" ></ param >
        
///   < returns ></ returns >
        
public  static string WebFormSHA1Encrypt(string data)
        {
            
if  (string.IsNullOrEmpty(data))
                throw new Exception("加密字符串不能为空");
            
return  FormsAuthentication.HashPasswordForStoringInConfigFile(data, "sha1");
        }

        #endregion
        #region 普通的字符变换加解密
        
///   < summary >
        
///  普通字符还变
        
///  加密
        
///   </ summary >
        
///   < param name = " str " ></ param >
        
///   < returns ></ returns >
        
public  static string CommonEncrypt(string data)
        {
            
if  (string.IsNullOrEmpty(data))
                throw new Exception("加密字符串不能为空");
            string result 
=  string.Empty;

            
int   len   =  data.Length;
            
for  ( int  i  =   0 ; i  <   len ; i ++ )
            {
                result 
+=  ( char )(data [ i ]   +   10   -   1   *   2 );
            }
            
return  result;
        }
        
///   < summary >
        
///  普通的字符变换
        
///  解密
        
///   </ summary >
        
///   < param name = " str " ></ param >
        
///   < returns ></ returns >
        
public  static string CommonDecrypt(string data)
        {
            
if  (string.IsNullOrEmpty(data))
                throw new Exception("加密字符串不能为空");
            string result 
=  string.Empty;
            
int   len   =  data.Length;
            
for  ( int  i  =   0 ; i  <   len ; i ++ )
            {
                result 
+=  ( char )(data [ i ]   -   10   +   1   *   2 );
            }
            
return  result;
        }


        #endregion


        #region 带有密钥的加解密

        private static readonly string KEY_64 
=  System.Configuration.ConfigurationManager.AppSettings [ "key_64" ] ;
        
///   < summary >
        
///  带有密钥的加解密
        
///  加密
        
///   </ summary >
        
///   < param name = "data" ></ param >
        
///   < returns ></ returns >
        
public  static string KeyEncrypt(string data)
        {
            using (DESCryptoServiceProvider provider 
=  new DESCryptoServiceProvider())
            {
                byte
[]  inputByteArray  =  Encoding.UTF8.GetBytes(data);
                provider.
Key   =  ASCIIEncoding. ASCII .GetBytes(KEY_64. Substring ( 0 8 ));
                provider.IV 
=  ASCIIEncoding. ASCII .GetBytes(KEY_64);

                MemoryStream ms 
=  new MemoryStream();
                using (CryptoStream cs 
=  new CryptoStream(ms, provider.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 
0 , inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.
Close ();
                }
                string 
str   =   Convert .ToBase64String(ms.ToArray());
                ms.
Close ();
                
return   str ;
            }
        }
        
///   < summary >
        
///  带有密钥的加解密
        
///  解密
        
///   </ summary >
        
///   < param name = "data" ></ param >
        
///   < returns ></ returns >
        
public  static string KeyDecrypt(string data)
        {
            byte
[]  inputByteArray  =   Convert .FromBase64String(data);
            using (DESCryptoServiceProvider provider 
=  new DESCryptoServiceProvider())
            {

                provider.
Key   =  ASCIIEncoding. ASCII .GetBytes(KEY_64. Substring ( 0 8 ));
                provider.IV 
=  ASCIIEncoding. ASCII .GetBytes(KEY_64);

                MemoryStream ms 
=  new MemoryStream();
                using (CryptoStream cs 
=  new CryptoStream(ms, provider.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 
0 , inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.
Close ();
                }
                string 
str   =  Encoding.UTF8.GetString(ms.ToArray());
                ms.
Close ();
                
return   str ;
            }
        }
        #endregion
    }
    
public  class
分享到:
评论

你可能感兴趣的:(算法,Security,webform,LINQ,WinForm)