是否可以像在 C++ 中那样在多个 .cs 文件中展开 C# class?

Is it possible to spread out a C# class in multiple .cs files like in c++?

在 C++ 中,您可以在单独的 cpp 文件中定义 class 的各个部分。例如,

Header:

// Header.h
class Example
{
public: 
    bool Func1();
    bool Func2();
};

CPP 1

//Func1.cpp
#include "Header.h"
bool Example::Func1()
{
    return true;
}

CPP 2

//Func2.cpp
#include "Header.h"
bool Example::Func2()
{
    return false;
}

在 C# 中是否可以做类似的事情?我正在制作服务器和客户端 classes,并且有一些方法永远不会被修改(例如 SendString、GetString、SendInt、GetInt 等),我想将它们与将要修改的方法分开根据收到的数据包类型主动更新。

有什么方法可以像我尝试做的那样组织代码,还是我只需要制作另一个 class 来保存所有不会被进一步修改的方法?

Partial class is approach - generally used for splitting auto-generated and user-authored code. See When is it appropriate to use C# partial classes? 适合使用它的情况。

重构代码以将 类 保留在单个文件中可能更好,因为它在 C# 源代码中更为常见。

一个选择是在小接口上使用扩展方法,并将单独紧密分组的方法放入单独的静态 类。

 // Sender.cs
 // shared functionality with narrow API, consider interface
 class Sender
 {
     public SendByte(byte byte);
 }

 // SenderExtensions.cs
 // extensions to send various types 
 static class SenderExtensions
 {
     public static SendShort(this Sender sender, uint value)
     {
        sender.SendByte(value & 0xff);
        sender.SendByte(value & 0xff00);
     }
 }

是的,我们可以在 C# 中做类似的事情。我们在 C# 中有部分 class。