是否可以在 C# 中进行单元测试或代码分析以确定 class 中是否使用了命名空间?

Is it possible in C# for a unit test or code analysis to determine if a namespace is being used in a class?

作为一项业务规则,我们不允许在另一个命名空间内使用特定 命名空间。

示例:

using X.A;  //Allowed
using X.B;  //Not allowed

namespace X.C
{
    const string abc = X.A.MyClass.ABC; //Allowed
    const string def = X.B.MyClass.DEF; //Not allowed, because we are using X.B

    public void MyMethod()
    {
        string ghi = X.A.MyClass.GHI; //Allowed
        string jkl = X.B.MyClass.JKL; //Not allowed because we are using X.B
        string mno = "X.B.MyClass.MNO"; //Allowed, because we are not accessing X.B
    }
}

是否可以通过单元测试和/或代码分析来控制这一点,以便我们可以更轻松地执行此业务规则,而不是依赖代码审查,后者很容易错过此类事情?假设这是可能的,你会怎么做?

这样的规则可以通过工具 NDepend that let's write code rule through C# LINQ queries, and check such rules live in Visual Studio and in your Build Process.

具体来说,这样的规则可能如下所示:

warnif count > 0 from n in Namespaces where 
 n.IsUsing ("NUnit.Core.Extensibility") &&
(n.Name == @"NUnit.Core.Builders")
select new { n, n.NbLinesOfCode }
// the namespace NUnit.Core.Builders
// shouldn't use directly 
// the namespace NUnit.Core.Extensibility
// because (TODO insert your reason)

...并且可以在 Visual Studio 中实时编辑和执行/强制执行此规则。

实际上,您只需单击 dependency graph or from the dependency matrix:

即可生成此类代码规则

自从 NDepend 提供和 API.

以来,此类规则也可以在单元测试中编写和执行

您可能也对我们的 white books concerning structuring code through namespaces and assemblies 感兴趣。

免责声明:我为 NDepend 工作。