上一篇文章中,遗留了一点问题,因此,在本问中做详细描述
http://www.cnblogs.com/yanchanggang/archive/2007/12/14/995185.html
描述:
在平常开发过程中,有的时候,需要为类,属性,方法等添加一些额外的信息,并且,可以在使用过程中,获得这些信息.
比如说,一般的程序设计中,对于一个数据库表,都会有一个类与之对应,但是,有的情况下,如数据库中字段叫Object_Id,而类中对应的字段叫ObjectId,有的时候,我们需要在程序中,能够把数据库的Object_Id和类中的ObjectId对应上,有的办法,就是弄个配置文件,一个一个的对应上,当然,本文中,就是用attribute了.
例子参照:
在web service中,经常的用到这样的描述:
[method(descript="")]
用于对方法的阐述
详细介绍:
先看一下代码:

Code
using System;
using System.Collections.Generic;
using System.Text;

namespace TestAttribute


{
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class PropertyTestAttribute:Attribute

{
readonly string mPropertyAlias;
public PropertyTestAttribute(string propertyAlias)

{
mPropertyAlias = propertyAlias;
}

public string PropertyAlias

{
get

{
return mPropertyAlias;
}

}
}
}

AttributeUsage参数介绍:
属性 AttributeUsage 提供声明属性的基础机制
ValidOn:
指定可以将属性赋给的程序元素(类、方法、属性、参数等)。该参数的有效值可以在 .NET Framework 中的 System.Attributes.AttributeTargets 枚举中找到。该参数的默认值是所有程序元素 (AttributeElements.All)。
.(参照:http://www.cnblogs.com/stzyw/archive/2005/10/07/249693.html) AllowMultiple:
单一用途和多用途属性可以使用
AttributeUsage定义属性的单一用途或多用途。即确定在单个字段上使用单一属性的次数。在缺省情况下,所有属性都是单用途的。在
AttributeUsage属性中,指定
AllowMultiple为
true,则允许属性多次附加到指定的类型上
.(参照:http://www.cnblogs.com/stzyw/archive/2005/10/07/249693.html)
Inherited:指定继承属性规则
在AttributeUsageAttribute属性的最后部分是继承标志,用于指定属性是否能被继承。缺省值是false。然而,若继承标志被设置为true,它的含义将依赖于AllowMultiple标志的值。若继承标志被设置为true,并且AllowMultiple标志是flag,则改属性将忽略继承属性。若继承标志和AllowMultiple标志都被设置为true,则改属性的成员将与派生属性的成员合并
使用介绍:
代码:

Code
using System;
using System.Collections.Generic;
using System.Text;

namespace TestAttribute


{
public class TestPropertyAttribute

{
public TestPropertyAttribute()

{

}

private string mMyProperty;

[PropertyTest("测试的属性的描述")]
public string MyProperty

{
get

{
return mMyProperty;
}
set

{
mMyProperty = value;
}
}
}
}

操作介绍:

Code
Type typeTestPropertyAttribute = Type.GetType("TestAttribute.TestPropertyAttribute");

foreach (Attribute myClassAttribute in typeTestPropertyAttribute.GetCustomAttributes(true))

{
PropertyTestAttribute test = myClassAttribute as PropertyTestAttribute;
if (test != null)

{
Console.WriteLine(test.PropertyAlias.ToString());
}
}

foreach(PropertyInfo propertyInfo in typeTestPropertyAttribute.GetProperties())

{
foreach (Attribute myAttribute in propertyInfo.GetCustomAttributes(true))

{
PropertyTestAttribute test = myAttribute as PropertyTestAttribute;
if (test != null)

{
Console.WriteLine(test.PropertyAlias.ToString());
}
}
}

Console.ReadLine();
相关文章连接:
http://edu.100down.com/it/program/Csharp/105717776.htmlhttp://www.cnblogs.com/stzyw/archive/2005/10/07/249693.html
遗留问题描述:
1:根据属性的描述,设置属性值