c# - 如何将简单的 .cs 文件组合成一个 .cs 文件,所有用途都在顶部以便编译

标签 c# powershell

所以我知道一般来说,这是不可能的,因为Jon Skeet said so .

但是我的 .cs 文件是简单的类,在顶部有一个或两个 usings。我需要一个包含所有类的文件,这样我就可以将它作为单个文件粘贴到 Web 浏览器 IDE 中进行编译和运行。

我尝试使用 PowerShell,并将所有文件复制到一个文件中,如下所示:

get-content *.cs | out-file bigBadFile.cs

但是这个文件不会编译,因为它中间有 usings,这是不允许的:

CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations

如果您对我为什么需要它感到好奇 - 它用于 CodinGame 平台,我厌倦了将所有代码保存在一个文件中。

要合并的示例文件:

游戏数据.cs:

using System.Collections.Generic;

public class GameData
{
    public GameData(int width, int height)
    {
       ...
    }

    public int Width { get; set; }
    public int Height { get; set; }
    public List<int> List { get; set; }
    ...
}

播放器.cs:

using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;

public class Player
{
    private static string[] inputs;
    private static bool isFirstTurn = true;
    public static StringBuilder MoveBuilder;

    public static GameData Game;

    static void Main()
    {
     ...
    }
}

最佳答案

只是为 your own helpful answer 提供一个更简洁、更快速的 PSv4+ 替代方案 :

$usings, $rest = (Get-Content *.cs).Where({ $_ -match '^\s*using\s' }, 'Split')

# Encoding note: Creates a BOM-less UTF-8 file in PowerShell [Core] 6+,
#                and an ANSI file in Windows PowerShell. Use -Encoding as needed.
Set-Content bigBadFile.txt -Value (@($usings | Select-Object -Unique) + $rest)

关于c# - 如何将简单的 .cs 文件组合成一个 .cs 文件,所有用途都在顶部以便编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61697680/

相关文章:

c# - MVC 属性路由不起作用

c# - 为什么将 List<Term> 的参数重构为 IEnumerable<Term>?

powershell sendkeys 无法与阿拉伯字符正常工作

regex - 正则表达式排除不起作用的字符

sql - 多线程帮助/Powershell

c# - 从浏览器调用Windows服务

c# - 使用 Json.Net 在 MVC 中返回未转义的 Json

c# - 不对 TPL 任务对象调用 Dispose() 是否可以接受?

powershell - 如何使用 PowerShell 访问 "Custom"或非系统 TFS 工作项字段?

powershell - 以表格格式显示二维数组