I recently used it to add custom attributes to fields in my enum:
public enum ShapeName
{
// Lines
[ShapeDescription(ShapeType.Line, "Horizontal Scroll Distance", "The horizontal distance to scroll the browser in order to center the game.")]
HorizontalScrollBar,
[ShapeDescription(ShapeType.Line, "Vertical Scroll Distance", "The vertical distance to scroll the browser in order to center the game.")]
VerticalScrollBar,
}
Using reflection to get the field:
public static ShapeDescriptionAttribute GetShapeDescription(this ShapeName shapeName)
{
Type type = shapeName.GetType();
FieldInfo fieldInfo = type.GetField(shapeName.ToString());
ShapeDescriptionAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(ShapeDescriptionAttribute), false) as ShapeDescriptionAttribute[];
return (attribs != null && attribs.Length > 0) ? attribs[0] : new ShapeDescriptionAttribute(ShapeType.NotSet, shapeName.ToString());
}
The attribute class:
[AttributeUsage(AttributeTargets.Field)]
public class ShapeDescriptionAttribute: Attribute
{
#region Constructor
public ShapeDescriptionAttribute(ShapeType shapeType, string name) : this(shapeType, name, name) { }
public ShapeDescriptionAttribute(ShapeType shapeType, string name, string description)
{
Description = description;
Name = name;
Type = shapeType;
}
#endregion
#region Public Properties
public string Description { get; protected set; }
public string Name { get; protected set; }
public ShapeType Type { get; protected set; }
#endregion
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…