How could Reflection not lead to code smells?

后端 未结 18 2115
失恋的感觉
失恋的感觉 2020-12-12 15:02

I come from low level languages - C++ is the highest level I program in.

Recently I came across Reflection, and I just cannot fathom how it could be used without cod

18条回答
  •  情深已故
    2020-12-12 15:18

    One usage not yet mentioned: while reflection is generally thought of as "slow", it's possible to use Reflection to improve the efficiency of code which uses interfaces like IEquatable when they exist, and uses other means of checking equality when they do not. In the absence of reflection, code that wanted to test whether two objects were equal would have to either use Object.Equals(Object) or else check at run-time whether an object implemented IEquatable and, if so, cast the object to that interface. In either case, if the type of thing being compared was a value type, at least one boxing operation would be required. Using Reflection makes it possible to have a class EqualityComparer automatically construct a type-specific implementation of IEqualityComparer for any particular type T, with that implementation using IEquatable if it is defined, or using Object.Equals(Object) if it is not. The first time one uses EqualityComparer.Default for any particular type T, the system will have to go through more work than would be required to test, once, whether a particular type implements IEquatable. On the other hand, once that work is done, no more run-time type checking will be required since the system will have produced a custom-built implementation of EqualityComparer for the type in question.

提交回复
热议问题