反射。我们可以实现使用它吗? [英] Reflection. What can we achieve using it?

查看:150
本文介绍了反射。我们可以实现使用它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅​​读和学习反映在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
}

这篇关于反射。我们可以实现使用它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆