C#高级编程之“代码属性”
来源:互联网 发布:es java api 工具类 编辑:程序博客网 时间:2024/05/12 06:06
主要通过一个示例来解释这个概念。
这个示例主要用来当方法中出现异常后,能显示编写该 方法的作者信息,以便修改。
代码如下:
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();
}
}
}
- C#高级编程之“代码属性”
- C#高级编程之“代码属性”
- C#高级编程之“代码属性”
- C#高级编程之“代码属性”
- C#高级编程 - 小鸟系列之代码段管理
- C#高级编程之“反射”
- C#高级编程之“反射”
- c#高级编程之常量
- C#高级编程之C#语言
- C#高级编程笔记之.NET体系结构
- c#高级编程之派生的接口
- C#高级编程之委托 简明教程
- C#高级属性
- c#之跟踪(c#高级编程系列)
- 有关c#高级编程之---图形编程GDI+
- C#之属性及其示范代码
- C#编程之自动实现的属性
- 读书笔记(C#高级编程)
- 国产手机设计业遭遇拐点 萧条期寻觅突围路
- ASP.NET2.0学习4--ObjectDataSource(对数据绑定1的补充)
- asp动态树菜单集合(2/3)
- 二叉搜索树的基本操作(C代码实现)
- 毕业了背包去流浪(一)
- C#高级编程之“代码属性”
- 今天早晨参加了一次 code inspection
- 毕业了背包去流浪(二)
- 移植遇到的问题
- 毕业了背包去流浪(三)
- 再不愿错过——GCC与GDB
- 《合金装备4》的秘密!小岛秀夫访谈录
- 在UBUNTU 6.06(Dapper Drake)安装LAMP
- v0.0.3