Gần đây tôi đã sử dụng nó để thêm tùy chỉnh thuộc tính cho các trường trong enum của tôi:
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,
}
Sử dụng phản ánh để có được trên sân:
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());
}
Lớp thuộc tính:
[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
}
Nguồn
2009-12-13 21:06:34
câu hỏi liên quan: http://stackoverflow.com/questions/1859902/in-3-minutes-what-is-reflection –
liên quan có, nhưng cá nhân tôi nghĩ rằng câu hỏi đó là khá vô ích. Tích hợp là đạo hàm ngược lại là phép tính, nhưng tôi cá là nói với bạn rằng bạn đã dạy bạn không có gì, ngay cả khi bạn biết đạo hàm là gì. : D –