Use-cases for reflection

后端 未结 9 2164
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 20:34

Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in o

9条回答
  •  青春惊慌失措
    2020-12-08 21:06

    I generally use reflection for debugging. Reflection can more easily and more accurately display the objects within the system than an assortment of print statements. In many languages that have first-class functions, you can even invoke the functions of the object without writing special code.

    There is, however, a way to do what you want(ed). Use a hashtable. Store the fields keyed against the field name.

    If you really wanted to, you could then create standard Get/Set functions, or create macros that do it on the fly. #define GetX() Get("X") sort of thing.

    You could even implement your own imperfect reflection that way.

    For the advanced user, if you can compile the code, it may be possible to enable debug output generation and use that to perform reflection.

提交回复
热议问题