反射.我们可以用它来实现什么?

Jon*_*han 13 c# reflection .net-3.5

我正在阅读和学习C#中的反射.很高兴知道它对我的日常工作有什么帮助,所以我希望有比我更多经验的人告诉我关于使用它可以实现什么样的事情的样本或想法,或者我们如何减少代码量我们写的.

谢谢.

Cor*_*ton 11

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

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,
}
Run Code Online (Sandbox Code Playgroud)

使用反射获取字段:

    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());
    }
Run Code Online (Sandbox Code Playgroud)

属性类:

[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
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*nes 10

一般而言,Reflection允许您访问有关对象的元数据.将Reflection与其他技术相结合,可以使您的程序更具动态性.例如,您可以加载DLL并确定它是否包含接口的实现.您可以使用它来发现运行时支持功能的dll.Use可以使用它来扩展应用程序而无需重新编译,也无需重新启动它.

Visual Studio中的Intellisense使用反射为您提供有关您正在使用的对象的信息.

请注意,使用Reflection需要付出代价.反射物体可能很慢.但如果你需要它,Reflection是一个非常有用的工具.