简体   繁体   English

是否可以通过反射检查类型是否在使用块中(调用了Dispose)

[英]Is it possible to check via reflection that type is in using block (Dispose is called)

I need to find automatically all code that not disposed properly. 我需要自动查找所有未正确处理的代码。 Is it possible to check via reflection that my type N is used inside using statement (Dispose is called)? 是否可以通过反射检查我的类型N是否在using语句(调用Dispose)内使用?

No. The closest you could come is to add a finalizer - possibly conditionally so that it's only included for debug builds - which checks whether or not you've been disposed and logs the problem otherwise. 否。您可能会最接近的是添加一个终结器(可能有条件地添加它,以便仅将其包含在调试版本中),该终结器将检查您是否已处置,否则记录问题。 (You'd probably want to keep the stack trace on construction in this case, in order to blame the right code.) (在这种情况下,您可能想要使堆栈跟踪构造,以便责怪正确的代码。)

Bear in mind that adding finalizers will cause garbage to stick around for longer - although in your Dispose call you could suppress finalization, so correct code wouldn't have a significant penalty, other than generating the stack trace on construction... 请记住,添加终结器将导致垃圾停留更长的时间-尽管在Dispose调用中您可以抑制终结器,所以正确的代码不会产生重大损失,除了在构造过程中生成堆栈跟踪外...

Now that's all assuming you want to do things at execution time. 现在,所有这些都假设您想在执行执行操作。 There are various static analysis tools (such as the code analysis built into Visual Studio ) which will tell you at build time if it looks like you haven't disposed of everything appropriately. 有各种各样的静态分析工具(例如Visual Studio中内置代码分析 )会在构建时告诉您是否似乎没有适当地处理所有事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM