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

前端 未结 11 1670
天命终不由人
天命终不由人 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 14:58

    Really, reflection should be thought of as sort of an amplifier for code. It can make good code better and cleaner, and bad code worse. What does it do? It really allows you to write code, that your not totally certain what it's going to do at the time you write it. You have a general idea, but it allows you to not code what objects, methods, and properties are going execute when the program is compiled.

    Other posts are correct when they say it allows the program to execute code based on configuration values, but it's real power is that it allows you to severely bend the rules of object oriented programming. That's really what it does. It's kind of like turning the safety measures off. Private methods and properties can be accessed through reflection along with just about anything else.

    An excellent example of when MS uses reflection is with data binding on data object. You specify the name of the text field and data field for an object to bind to a drop down list etc., and the code reflects the object and pulls out the appropriate information. The data binding object does the same process over and over again, but it doesn't know what type of object it has to bind with. Reflection is a convenient way of writing a little bit of code to handle all the possible cases.

提交回复
热议问题