以下是我的.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;
}
这仍然无效:(
答案 0 :(得分:0)
我如何利用CommonSpace的System.IO,System.Text.RegularExpressions命名空间公开的类。
您不能:语言规范是using
语句的作用域仅限于声明它们的编译单元或名称空间主体。实际上,这意味着它们在声明所在的文件之外永远不可见,对于您的CommonSpace
来说,它们的范围仅限于大括号内。
More details in the C# language specification
这有一个很好的理由:如果您想知道一段代码中的类正在使用哪个名称空间,它就在文件中。如果其他地方的所有using指令都泄漏到您的名称空间中,那么名称冲突就不会有任何问题了。
如果文件中确实使用了太多使用指令,那么您的设计可能是错误的,应将类拆分为较小的单元。