Why is the use of reflection in .NET recommended?

后端 未结 9 654
再見小時候
再見小時候 2020-11-30 22:25

Is it definitely a good practice to use it?

What are some possible situations in a project that need reflection?

9条回答
  •  温柔的废话
    2020-11-30 22:50

    The main value of Reflection is that it can be used to inspect assemblies, types, and members. It's a very powerful tool for determining the contents of an unknown assembly or object and can be used in a wide variety of cases.

    Opponents of Reflection will cite that it is slow, which is true when compared to static code execution--however Reflection is used throughout the .NET framework, and provided that it's not abused it can be a very powerful tool in the toolkit.

    Some useful applications:

    • Determining dependencies of an assembly

    • Location types which conform to an interface, derive from a base / abstract class, and searching for members by attributes

    • (Smelly) testing - If you depend on a class which is untestable (ie it doesn't allow you to easily build a fake) you can use Reflection to inject fake values within the class--it's not pretty, and not recommended, but it can be a handy tool in a bind.

    • Debugging - dumping out a list of the loaded assemblies, their references, current methods, etc...

提交回复
热议问题