C# 命名空间(Namespace)

声明、嵌套、`using` 别名、`global using`、以及程序集。

Beginner
Key Points命名空间是逻辑分组(避免重名),程序集是物理分组(一个 dll)。

声明

C#
namespace Shop.Models
{
    class Product
    {
        public string Name { get; set; } = "";
    }
}

namespace Shop.Services
{
    class ProductService
    {
        public string Describe(Models.Product p) => "商品:" + p.Name;
    }
}

var s = new Shop.Services.ProductService();
Console.WriteLine(s.Describe(new Shop.Models.Product { Name = "键盘" }));
Output
商品:键盘
C#
// 文件范围命名空间(C# 10+),整个文件都属于它
namespace Shop.Models;

class Order
{
    public int Id { get; set; }
}

// 上面这个 Order 的全名是 Shop.Models.Order

嵌套与全名

C#
namespace A
{
    namespace B
    {
        class C
        {
            public static string Name => "A.B.C";
        }
    }
}

// 两种写法等价
namespace A.B
{
    class D { }
}

Console.WriteLine(A.B.C.Name);
Console.WriteLine(typeof(A.B.D).FullName);
Output
A.B.C
A.B.D

using

C#
using System.Text;
using System.Collections.Generic;

// 别名
using StrList = System.Collections.Generic.List<string>;
using Dict = System.Collections.Generic.Dictionary<string, int>;

// 静态导入(C# 6):直接用静态成员
using static System.Math;
using static System.Console;

var list = new StrList { "a", "b" };
var map = new Dict { ["x"] = 1 };

WriteLine(string.Join(",", list));
WriteLine(map["x"]);
WriteLine(Sqrt(16));
WriteLine(Max(3, 7));
Output
a,b
1
4
7

With using static System.Math you write Sqrt(16) instead of Math.Sqrt(16). Great for math-heavy code, though it blurs what is local versus imported.

global using

C#
// GlobalUsings.cs —— 全项目生效,不用每个文件重复写
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading.Tasks;

// 项目文件里开启隐式 using 后,上面这些大部分自动包含
XML
<PropertyGroup>
  <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

ImplicitUsings adds System, System.Linq, System.Collections.Generic and friends automatically per project type. Put your own frequently used namespaces in GlobalUsings.cs.

命名空间 vs 程序集

ConceptNatureUnit
命名空间逻辑避免重名,可跨程序集
程序集物理一个 .dll / .exe

System.String lives in System.Runtime.dll while System.Linq.Enumerable lives in System.Linq.dll. One namespace can span assemblies and one assembly can hold many namespaces.

Name company projects with a reversed domain: Com.MyCorp.Project.Module. It avoids collisions and shows ownership at a glance.

Friends & Partners