What exactly is Reflection and when is it a good approach?

前端 未结 11 1696
天命终不由人
天命终不由人 2020-12-25 14:58

What exactly is Reflection? I read the Wikipedia article on this subject and I understand that it is a kind of meta-programming, where the program can modify itself at run-

11条回答
  •  孤独总比滥情好
    2020-12-25 15:11

    It's not so much modifying code at execution time, but examining objects and asking them to execute code without knowing their type statically.

    One simple way of describing it would be "a somewhat painful way of making a statically typed language behave dynamically."

    EDIT: Uses:

    • Configuration (e.g. take an XML file which specifies types and properties, then construct appropriate objects)
    • Testing (unit tests which are identified by name or attributes)
    • Web services (in .NET at least, a lot of reflection is used in the core web service engine)
    • Automatic event wiring - provide a method with an appropriate name, e.g. SubmitButton_Click and ASP.NET will attach that method as a handler for the SubmitButton's Click event (if you have autowiring turned on)

    Is it a good idea? Well, only when the alternatives are painful. I prefer static typing when it doesn't get in the way - then you get lots of compile-time goodness, and it's faster too. But when you do need it, reflection lets you do various things which otherwise just wouldn't be possible.

提交回复
热议问题