反射。我们可以实现使用它吗?可以实现、反射、使用它

由网友(回忆再美终是空°)分享简介:我在阅​​读和学习反映在C#。这将是罚款,知道它是如何能帮助我在我的日常工作​​,所以我希望人们有更多的经验比我告诉我的样品或想法什么样的事情,我们可以实现使用它,或者我们如何能减少德金额$的我们写C $℃。I'm reading and learning about reflection in C#. It wou...

我在阅​​读和学习反映在C#。这将是罚款,知道它是如何能帮助我在我的日常工作​​,所以我希望人们有更多的经验比我告诉我的样品或想法什么样的事情,我们可以实现使用它,或者我们如何能减少德金额$的我们写C $℃。

I'm reading and learning about reflection in C#. It would be fine to know how can it help me in my daily work, so I want people with more experience than me tell me samples or ideas about what kinds of things can we achieve using it, or how can we reduce de amount of code that we write.

感谢。

推荐答案

最近,我用它来添加自定义属性在我的枚举字段:

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());
    }

属性类:

[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
}
阅读全文

相关推荐

最新文章