NDepend CQL 查询缺少 IDisposable 实现

2023-12-28

我意识到这个问题正在寻找的查询不足以找到 IDisposable 实现的每个小问题,但每个早期警告都很重要,所以我会采取我能得到的。

我想知道是否有人提出了一个 NDepend 的 CQL 查询,该查询将列出所有未实现 IDisposable 但具有一个或多个字段的类。一个类可能会通过错误(即,有人忘记检查 IDisposable 实现的字段类型)或通过代码演变(即,在某处的字段中使用的类在某个位置附加 IDisposable )而出现在该查询的结果列表中。稍后的日期,所有用法均未更新)。

查找所有未实现 IDisposable 的类的简单查询是:

SELECT TYPES WHERE !Implement "System.IDisposable"

但是,这当然不会检查该类是否should为上述规则实现 IDisposable。

有人有这样的疑问吗?我仍在掌握 CQL,所以这部分内容让我无法理解。


Lasse,感谢 CQLinq(LINQ 上的代码规则)功能,现在可以匹配应该实现 IDisposable 的类型。实际上现在提供了两个相关的默认规则,您可以轻松编写自己的相关规则:

  • 具有一次性实例字段的类型必须是一次性的 http://www.ndepend.com/DefaultRules/webframe.html?Q_Types_with_disposable_instance_fields_must_be_disposable.html
  • 具有非托管资源的一次性类型应声明终结器 http://www.ndepend.com/DefaultRules/webframe.html?Q_Disposable_types_with_unmanaged_resources_should_declare_finalizer.html

// <Name>Types with disposable instance fields must be disposable</Name>
warnif count > 0

let iDisposable = ThirdParty.Types.WithFullName("System.IDisposable").FirstOrDefault() 
where iDisposable != null // iDisposable can be null if the code base doesn't use at all System.IDisposable

from t in Application.Types where 
   !t.Implement(iDisposable) && 
   !t.IsGeneratedByCompiler 

let instanceFieldsDisposable = 
    t.InstanceFields.Where(f => f.FieldType != null &&
                                f.FieldType.Implement(iDisposable))

where instanceFieldsDisposable.Count() > 0
select new { t, instanceFieldsDisposable }

// <Name>Disposable types with unmanaged resources should declare finalizer</Name>
// warnif count > 0
let iDisposable = ThirdParty.Types.WithFullName("System.IDisposable").SingleOrDefault()
where iDisposable != null // iDisposable can be null if the code base deosn't use at all System.IDisposable

let disposableTypes = Application.Types.ThatImplement(iDisposable)
let unmanagedResourcesFields = disposableTypes.ChildFields().Where(f => 
   !f.IsStatic && 
    f.FieldType != null && 
    f.FieldType.FullName.EqualsAny("System.IntPtr","System.UIntPtr","System.Runtime.InteropServices.HandleRef")).ToHashSet()
let disposableTypesWithUnmanagedResource = unmanagedResourcesFields.ParentTypes()

from t in disposableTypesWithUnmanagedResource
where !t.HasFinalizer
let unmanagedResourcesTypeFields = unmanagedResourcesFields.Intersect(t.InstanceFields)
select new { t, unmanagedResourcesTypeFields }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NDepend CQL 查询缺少 IDisposable 实现 的相关文章

随机推荐