现有库扩展的 C# 命名空间命名约定

C# Namespace naming conventions for extensions of existing libs

我在我的项目中使用开源库,我知道如何扩展它。但是如果有一天我发布它,我希望命名空间名称是正确的。我已经检查了具有命名约定的文档,但其中 none 描述了如何为现有库的扩展命名名称空间。

例如,我正在扩展 SomeLibrary。它有命名空间 SomeLibrary.Types,我想通过向它添加一些我的类型来扩展它。所以问题是:我应该如何命名我的项目中的命名空间?

我可以使用 SomeLibrary.Types 命名空间吗?使用其他人的命名空间是否正确,或者我应该将我的库命名空间与我扩展的库的命名空间区分开来?我已经看到一些扩展现有库的库使用相同的名称空间,例如 Microsoft.EntityFrameworkCore.InMemory 使用 Microsoft.EntityFrameworkCore 名称空间作为它的 UseInMemoryDatabase 方法,但我认为这不是一个好方法例如。

如果我不应该这样命名,请问我应该如何命名项目中的名称空间,以扩展现有名称空间?

有几篇关于命名空间指南和最佳实践的文章。最佳做法是意见,会随着时间而改变。

让我们从您的项目 open-source 开始,您看到最终会得到扩展。

  1. 尽可能不要延长它。它是开源的,允许您在考虑扩展之前做一些事情。首先,如果您为开源编写的功能有意义,您可以为其做出贡献。其次,您可以分叉存储库并使用您添加的功能维护您自己的副本。

  2. 如果必须扩展它,应将其打包并作为 NuGet 包分发。如果你走这条路,这里有一些 guidance on open-source libraries in general. One thing I didn't see in there was consider using the same license for your code as the code you're extending. And here is some more detail on the namespace guidance

此案例值得注意:

✔️ DO prefix namespace names with a company name to prevent namespaces from different companies from having the same name.

❌ DO NOT give the same name to types in namespaces within a single application model.

您遗漏的一点是您是否正在使用实例类型进行扩展,例如 class 或接口的实现或扩展方法。这有点不同。

This article from Microsoft Docs 有一些针对扩展方法的指南

❌ DO NOT put extension methods in the same namespace as the extended type unless it is for adding methods to interfaces or for dependency management.

✔️ CONSIDER defining extension methods in the same namespace as the extended type if the type is an interface and if the extension methods are meant to be used in most or all cases.