如何创建 fxcop 规则来检查一个类是否在另一个类的构造函数中调用 init ?
假设我有类 A,它实例化了类 B。类 B 有一个构造函数和几个 init 方法(通过类接口强制执行)。如何编写 fxcop 规则来检查实例化 B 后至少调用一个 init 方法。
如果您在运行时从互联网加载它,则无法使用构造函数,因此 init.
Let's say I have class A which instantiates class B. class B has a constructor and several init methods (enforced through a class interface). How to write fxcop rule to check that at least one init method is called after instantiating B.
What if you load it at runtime from internet you cannot use constructor so the init.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了最琐碎的情况之外,这种规则几乎不可能编写。例如,如果您想确保在调用 B 构造函数后立即调用 B init 方法,则可以相对轻松地完成(尽管分支逻辑即使在此处也可能会导致问题)。但是,如果只需要支持这种琐碎的用法,则不需要单独的 init 方法。通常更有趣的检测是在调用 B 实例的 init 方法之前尝试对 B 实例执行其他操作的情况,而这对于像 FxCop 这样的静态验证器来说并不是真正的工作。
您是否考虑过如果 B 在进入另一个方法时未初始化,则从 B 抛出异常(就像可能从已处置的实例中抛出 ObjectDisposeException 一样)?
This sort of rule is nearly impossible to write except for the most trivial cases. For example, if you want to ensure that a B init method is called immediately after invoking a B constructor, that can be done relatively easily (although branching logic can cause problems even there). However, there wouldn't be much need for a separate init method if one only needed to support such trivial usage. What is generally more interesting to detect are cases where one attempts to do something else with a B instance before invoking its init method, and that's not really a job for a static verifier like FxCop.
Have you considered throwing an exception from B if it is not initialized at entry into another method (much like one might throw an ObjectDisposedException from a disposed instance)?