作为一项业务规则,我们不允许在另一个命名空间内使用特定命名空间。
示例:
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 可以实现这样的规则。 ,和check such rules live in Visual Studio和 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来生成这样的代码规则。或来自dependency matrix :
这样的规则也可以在单元测试中编写和执行,因为 NDepend 提供了 API .
您可能也对我们的 white books concerning structuring code through namespaces and assemblies 感兴趣.
免责声明:我为 NDepend 工作。
关于c# - 在 C# 中是否可以通过单元测试或代码分析来确定类中是否使用了命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37688275/