NDepend CQL查询缺失IDisposable实现

5
我知道这个问题所寻找的查询并不足以找出每一个IDisposable实现中的小问题,但早期的警告也很重要,所以我会尽力而为。
我想知道是否有人已经想出了一个CQL查询,可以列出所有没有实现IDisposable的类,但是有一个或多个字段实现了IDisposable。一个类可能会出现在此查询的结果列表中,无论是通过错误(即某人忘记检查IDisposable实现的字段类型),还是通过代码演化(即在稍后的日期上添加IDisposable到某个字段中的类,而未更新所有用法)。
查找所有没有实现IDisposable的类的简单查询是:
SELECT TYPES WHERE !Implement "System.IDisposable"

然而,这当然不会检查上述规则中是否应该实现IDisposable接口。

有人有这样的查询吗?我还在努力掌握CQL,所以这部分让我困惑。

1个回答

8
由于CQLinq(Code Rule over LINQ)的功能,现在可以匹配应该实现IDisposable的类型。实际上,现在提供了两个相关的默认规则,您可以轻松编写自己相关的规则:
// <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 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接