简体   繁体   English

C#局部类

[英]C# partial class

如何在C#中的多个文件和不同的命名空间中编程局部类?

You can't. 你不能 From here ... 这里 ...

Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace 使用partial关键字表示可以在名称空间中定义类,结构或接口的其他部分

Must be in the same namespace. 必须在相同的名称空间中。

Per comment: Here's an article that discusses defining a namespace cross multiple assemblies. 每条评论:这是一篇文章 ,讨论跨多个程序集定义名称空间。 From there ... 从那里 ...

Strictly speaking, assemblies and namespaces are orthogonal. 严格来说,程序集和名称空间是正交的。 That is, you can declare members of a single namespace across multiple assemblies, or declare multiple namespaces in a single assembly. 也就是说,可以在多个程序集中声明单个名称空间的成员,也可以在单个程序集中声明多个名称空间。

You cannot have a partial class in multiple namespaces. 您不能在多个名称空间中使用局部类。 Classes of the same name in different namespaces are by definition different classes . 根据定义,不同名称空间中同名的类是不同的类

A partial class (as any other class) needs to live in one single namespace (otherwise its another class). 局部类(与其他任何类一样)需要存在于一个单独的命名空间(否则为另一个类)中。

To split it between different files just use the partial keyword after the access keyword: 要在不同文件之间进行拆分,只需在access关键字之后使用partial关键字:

// this bit of the class in a file
public partial class Employee
{
    public void DoWork()
    {
    }
}

//this bit in another file
public partial class Employee
{
    public void GoToLunch()
    {
    }
}

You can't. 你不能 A partial class means just that: A single class broken into several files. 局部类仅意味着:单个类分为多个文件。 That also means that all files that this partial class consists of must have the same namespace. 这也意味着此局部类组成的所有文件都必须具有相同的名称空间。 Otherwise it wouldn't be the same class anymore. 否则它将不再是同一个类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM