Reflection. What can we achieve using it?

2020-02-03 06:47发布

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.

Thanks.

14条回答
走好不送
2楼-- · 2020-02-03 07:26

I guess that a "stand alone" application, where every object you use is known at compile time, you don't use reflection much.

But when you write library or framework code that should use objects that are not known (completely - you might know about interfaces or baseclasses) at compile time, reflection could be invaluable to work with those objects.

查看更多
Emotional °昔
3楼-- · 2020-02-03 07:27

Generally speaking Reflection allows you access to metadata about objects. Combining Reflection with other techniques allows you to make your program more dynamic. For instance you can load a DLL and determine if it contains an implementation of an interface. You could use this to discover dll's that support functionality at runtime. Use could use this to extend an application without a recompilation and without having to restart it.

Intellisense in Visual Studio uses reflection to give you information about the objects you are using.

Note that using Reflection comes at a cost. Reflecting an object can be slow. But if you need it Reflection is a very usefull tool.

查看更多
Deceive 欺骗
4楼-- · 2020-02-03 07:33

Here are some things I've used Reflection for that would be extremely difficult or impossible without it:

  • My C# port of the StringTemplate templating engine. Reflection is used to retrive properties of dynamic objects.
  • A CLI JIT compiler written in managed code.

The Managed Extensibility Framework (a new .NET library) uses reflection to:

  • Locate and compose parts, including applying Imports.
  • It avoids loading assemblies for execution until their contents are required.
查看更多
forever°为你锁心
5楼-- · 2020-02-03 07:34

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
}
查看更多
看我几分像从前
6楼-- · 2020-02-03 07:35

One use among many: you can make a plug-in architecture where you specify the name of the class-to-use in a configuration file. Using reflection you can take this string and create an instance of the object requested. If that object implements a known interface, then you can use it through ordinary (non reflection) code.

查看更多
Evening l夕情丶
7楼-- · 2020-02-03 07:35

I've used reflection to allow me more flexibility meeting constantly changing requirements. That is, the customer kept changing their minds as to where to place a database table within a database. All I did was have the object self inspect its fields and call the object constructors of those fields within the object itself. Then, if one table should be found somewhere else? Click, paste, done.

This did not go out in final production, mind you, but during the iterative phase removed some of the boilerplate I would need to change.

查看更多
登录 后发表回答