【问题标题】:How to write a namespace which exposes common namespaces for avoiding multiple using statements in C#.NET如何编写一个暴露公共命名空间的命名空间,以避免在 C#.NET 中使用多个 using 语句
【发布时间】:2019-08-08 05:45:09
【问题描述】:

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

CommonSpace.cs

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

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

Program.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;
}

这仍然不起作用:(

【问题讨论】:

  • 作为您问题的旁注。 Read this article 来自 C# 语言最重要的开发人员之一
  • 目前还不清楚问题是什么以及您要达到的目标。有很多代码膨胀吗?通常,如果您发现在一个文件中使用太多,那么您可能可以分离一些职责。但是我不会仅仅因为 using 语句太多就去破解代码。我会查看实际的代码结构来决定。
  • 如果你使用的是 Visual Studio,你可以点击 ctrl + 。它将删除未使用的 using 语句。除此之外,Tamirs 的声明也很到位。
  • @Steve 感谢您的指点,但是,该类只是用于填充空间并且是一个假人。我已经更改了 CommonSpace.cs :)
  • @Tamir,你说得非常正确,我真的很想重组多个用途,但我想把我的多个用途包装成一个。

标签: c# .net namespaces refactoring


【解决方案1】:

如何使用由 CommonSpace 中的 System.IO、System.Text.RegularExpressions 命名空间公开的类。

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

More details in the C# language specification

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

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

【讨论】:

    猜你喜欢
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多