c# - 如何编写一个公开公共(public)命名空间的命名空间,以避免在 C#.NET 中使用多个 using 语句

标签 c# .net namespaces refactoring

以下是我的 .NET Core 应用程序代码。

CommonSpace.cs

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace CommonSpace
{
    class CommonSpace
    {
        //dummy class
    }
}

程序.cs
using System;
using CommonSpace;


namespace BackToBasicsApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            /*
            code which uses System.IO, System.Text.RegularExpressions from CommonSpace goes here
            */

        }
    }
}

我如何利用来自 CommonSpace 的 System.IO、System.Text.RegularExpressions 命名空间公开的类。
在重构我的一些代码时,这个问题让我感到震惊,我在类的顶部看到了很长的 using 语句列表。
这是一个非常基本的问题,所以请原谅我 BackToBasicness...;)

这是我修改后的 CommonSpace.cs
using System;

namespace CommonSpace
{
    using System.IO;
    using System.Linq;
    using System.Text.RegularExpressions;
}

这仍然不起作用:(

最佳答案

How do i make use of classes exposed by the System.IO, System.Text.RegularExpressions namespaces from CommonSpace.



你不能:语言规范是 using语句的范围仅限于声明它们的编译单元或命名空间主体。实际上,这意味着它们永远不会在声明所在的文件之外可见,在您的 CommonSpace 的情况下。它们的范围在花括号内。

More details in the C# language specification

这样做有一个很好的理由:如果您想知道一段代码中的类正在使用哪个命名空间,它就在文件中。如果来自其他地方的所有 using 指令都泄漏到您的命名空间中,那么名称冲突问题将永无止境。

如果您的文件中确实有太多 using 指令,那么您的设计可能是错误的,您应该将您的类拆分为更小的单元。

关于c# - 如何编写一个公开公共(public)命名空间的命名空间,以避免在 C#.NET 中使用多个 using 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55211510/

相关文章:

c# - TPL 数据流和控制台应用程序不会终止应用程序

xml - E4X:抓取带有命名空间的节点?

c++ - 为动态分配的整数赋值

c# - MVC应用架构的数据流

c# - ASP.NET 中的 SetFocus() 和 Focus() 有什么区别?

c# - 使用 C# 驱动程序反序列化嵌套类时 MongoDB 出错

c# - Azure:将控制台 application.exe.config(从 app.config 生成)复制到 Azure 包

.net - 如何从我的 Windows Mobile 5 设备中删除 .NET Compact Framework?

asp.net - 组织 Web 应用程序

c# - XSD 命名空间到 C# 命名空间