gpt4 book ai didi

c# - 在 C# 中是否可以通过单元测试或代码分析来确定类中是否使用了 namespace ?

转载 作者:行者123 更新时间:2023-11-30 23:24:38 24 4
gpt4 key购买 nike

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

例子:

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 Studioin 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 中实时编辑和执行/强制执行此规则。 NDepend Namespace Rule Edited in Visual Studio

实际上,您可以通过单击 dependency graph 生成这样的代码规则或来自 dependency matrix :

NDepend Dependency Graph

由于 NDepend 提供和 API,这样的规则规则也可以在单元测试中编写和执行.

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

免责声明:我为 NDepend 工作。

关于c# - 在 C# 中是否可以通过单元测试或代码分析来确定类中是否使用了 namespace ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37688275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com