如何在 C# 中从单独文件夹中的文件导入命名空间

How can I Import A Namespace from A File in A Seperate Folder in C#

当定义此 class 的文件位于另一个文件夹中时,如何将扩展方法(见下文)引入当前命名空间?

StringHandler.csProduct 文件夹中时,我可以将 using Utilities; 包含在 Product.cs 中,但是当它在单独的文件夹中时,与 Project 文件夹(在 Utilities 文件夹中),我不知道如何包含它。有人可以解释一下在这种情况下我如何使用 using 关键字吗?例如,using 真正指向我的文件系统的哪里(我是否需要指定相对于我的 csproj 文件或我的 CallCenter.sln 文件的使用目录?)?

│   CallCenter.sln
│
├───src
│   ├───Project
│   │   │   Product.cs
|   |   |   Project.csproj
│   │   ├───bin
│   │   │   └───...
│   │   │
│   │   └───obj
│   │       └───...         
│   │
│   └───Utilities
│           StringHandler.cs

StringHandler.cs

namespace Utilities
{
    public static class StringHandler
    {
        public static string InsertSpaces(this string source)
        {
            string result = string.Empty;

            if (!string.IsNullOrWhiteSpace(source))
            {
                foreach (char letter in source)
                {
                    if (char.IsUpper(letter))
                    {
                        result = result.Trim();
                        result += " ";
                    }
                    result += letter;
                }
            }
            return result.Trim();
        }
    }
}

.cs文件所在的文件夹在编译过程中没有意义。 using 语句只允许找到来自特定命名空间的类型。为了能够使用扩展方法,请确保:

  • 包含命名空间(using Utilities;)
  • 文件(StringHandler.cs)包含在您的项目中在您当前项目引用的另一个项目中

How do I bring into the current namespace an extension method (see below) into scope, when the file this class is defined in is in another folder?

文件的定义位置与文件夹无关。按照惯例,磁盘上的文件夹结构模仿命名空间,但它不是必须的。 A using "brings" 类型进入命名空间。 (不是真的 "brings" -- 更像是 "makes available to")。

就目标项目中的命名空间可用的源类型而言,它必须通过

在物理上对您的项目可用
  • 从目标项目直接引用源项目
  • 从目标项目直接引用源 NuGet 包
  • 通过目标项目中另一个项目的传递依赖间接引用源项目
  • 通过目标项目中另一个项目或 NuGet 包的传递依赖间接引用源 NuGet 包

逻辑上

  • 一个using语句到源类型

When StringHandler.cs is in the Product folder, I can include using Utilities; in Product.cs, but when it is in a separate folder, alongside the Project folder (in the Utilities folder), I can't figure out how to include it. Can someone please explain how I can use the using keyword in this case?

您不能使用 using 到达 StringHandler,因为您当前已经定义了结构。原因是 StringHandler 不是 任何项目的一部分。因为它不是任何项目的一部分,所以它违反了我上面列出的规则。

要按预期使用 using,您有两个简单的选择:

  • 直接将StringHandler添加到需要它的项目中,或者如果您希望将StringHandler分开,将其添加到另一个项目中并从目标项目中引用该项目。
  • 再功夫一点,将StringHandler留在原处(无项目)并在目标文件中包含一个link项目。这有点作弊:它让 StringHandler 看起来一直在 Project 中。这种情况很少见;我个人只在我想包括公共程序集属性时才这样做,例如,不常见 code.

For instance, where is using really pointing to on my file system (do I need to specify the using directory relative to my csproj file or to my CallCenter.sln file?)?

同样,忘记 directory/folder/disk 结构。只考虑解决方案中的物理引用(基于project/NuGet)和逻辑引用(基于命名空间)。他们通常匹配 directory/folder/disk,但他们不必匹配。