When do you use reflection? Patterns/anti-patterns

前端 未结 17 2280
旧时难觅i
旧时难觅i 2020-12-02 09:58

I understand the reflection API (in c#) but I am not sure in what situation would I use it. What are some patterns - anti-patterns for using reflection?

17条回答
  •  余生分开走
    2020-12-02 10:34

    I have used reflection in a number of places. The main broad categories include:

    1. Auto-generated GUIs (ie, a property editor). You can loop over the properties of an object and use a registry of UI element factories to build a form. I use attributes on properties to guide the UI creation.
    2. Serialization. I have written serialization frameworks the use reflection to serialize and deserialize objects.
    3. Web Services. Similar to serialization, I have used reflection to create and consume SOAP messages and also to generate WSDL.
    4. Domain Specific Languages. Interpreted scripting languages will typically bind to objects and methods using reflection.
    5. Debugging tools. Such tools can use reflection to examine the state of an object. Handy for creating log messages under fault conditions.

    Patterns wise, I'm not sure what the patterns are. A common thread between all the uses is reference by name and late binding - you want to bind to a member at runtime. This is often the case when you dynamically load assemblies and do not know the types of objeccts you need to create/manipulate.

    Using reflection is powerful, but it wont make you more popular at parties. Only use it where the coupling is intentionally weak. So weak that you expect it to break at runtime. A great example is data binding in WPF.

    I'm unsure about anti-patterns, but surely it would relate to doing things at runtime that should be done at compile time...

提交回复
热议问题