C#代码属性

主要通过一个示例来解释这个概念。

  这个示例主要用来当方法中出现异常后,能显示编写该 方法的作者信息,以便修改。

  代码如下:

using  System;

using  System.Collections.Generic;

using  System.Text;

using  System.Reflection ;

 

namespace  AttributeTest

{       

    
/// <summary>

    
/// 代码属性类

    
/// </summary>


    [AttributeUsage (AttributeTargets .Method 
| AttributeTargets .Class )]

    
public class CodeAttirbute:System .Attribute 

    
{

        
private string name = string.Empty;

        
private string email = string.Empty;

 

        
public CodeAttirbute(string initName,string initEmail)

        
{

            name 
= initName;

            email 
= initEmail;

        }


 

        
public string Name

        
{

            
get

            
{

                
return name;

            }


            
set

            
{

                name 
= value;

            }


        }


 

        
public string Email

        
{

            
get

            
{

                
return email;

            }


            
set

            
{

                email 
= value;

            }


        }


    }


 

    
/// <summary>

    
/// 工具类,通过自定义的代码属性查找某个方法的作者和Email

    
/// </summary>


    
public class AttributeTool

    
{

        
public AttributeTool()

        
{

        

        }


 

        
public static CodeAttirbute getAttirbute(MethodBase method)

        
{

            
/*

             * 返回由System.Type标识的自定义属性的数组

             * 很难理解,大概意思就是把该方法的代码属性类型化成CodeAttirbute的代码属性

            
*/


            
object [] attributes = method.GetCustomAttributes(typeof(CodeAttirbute), true);

            
return (CodeAttirbute )attributes[0];

        }


    }


 

    
/// <summary>

    
/// 使用上面的工具类,在出现异常后,显示该方法的作者信息

    
/// </summary>


    
public class UseAttributeTool

    
{

        
public UseAttributeTool()

        


        

        }


 

        [CodeAttirbute(
"1""2")]

        
public void test()

        
{

            
try

            
{

                
int a = 1;

                
int b = 0;

                
int c = a / b;

            }


            
catch (Exception e)

            
{

                Console.WriteLine(e.Message);

 

                
//MethodBase.GetCurrentMethod():返回表示当前正在执行的方法的MethodBase对象

                CodeAttirbute ca 
= AttributeTool.getAttirbute(MethodBase.GetCurrentMethod());

 

                
//显示代码属性

                Console.WriteLine(
"Name:{0},Email:{1}",ca.Name ,ca.Email );

            }


 

        }


 

        
static void Main()

        
{

            UseAttributeTool u 
= new UseAttributeTool();

            u.test();

            Console.Read();

        }


 

    }


 

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值