为什么推荐在 .NET 中使用反射? [英] Why is the use of reflection in .NET recommended?

查看:20
本文介绍了为什么推荐在 .NET 中使用反射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用它绝对是一个好习惯吗?

Is it definitely a good practice to use it?

项目中有哪些可能的情况需要反思?

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

推荐答案

Reflection 的主要价值在于它可以用于检查程序集、类型和成员.它是一种非常强大的工具,用于确定未知程序集或对象的内容,可用于多种情况.

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.

反射的反对者会指出它很慢,与静态代码执行相比,这是事实——但是反射在整个 .NET 框架中使用,并且只要它不被滥用,它就可以成为工具包中非常强大的工具.

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.

一些有用的应用:

  • 确定程序集的依赖项

  • 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) 测试——如果你依赖一个不可测试的类(即它不允许你轻松构建一个假的),你可以使用反射在类中注入假值——它不漂亮,不推荐,但它可以成为绑定中的一个方便的工具.

(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...

这篇关于为什么推荐在 .NET 中使用反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆