【问题标题】:Merging namespaces in C#在 C# 中合并命名空间
【发布时间】:2014-07-02 08:53:19
【问题描述】:

如何将分散在不同文件中的相同命名空间合并到一个文件中? 我正在使用 Resharper,但它似乎没有这个选项。

顺序并不重要。

类似:copy *.cs output.cs,但这不会合并命名空间。

【问题讨论】:

  • 我认为没有预定义的方法可以做到这一点。您不能反复检查文件(按文本查找)是否有类似的命名空间声明?
  • 你为什么要这样做?一个文件中的多个类并不完全是'come il faut' :-)
  • 这样做有什么好处?为什么要将所有内容都放入一个代码文件中?这只会使维护更加困难。
  • 大声笑,给我十分钟左右。
  • 在命名空间中排序代码的正确方法是:命名空间的文件夹,类的文件。为什么要将一个命名空间中的所有类放在一个文件中?

标签: c# visual-studio-2012 namespaces


【解决方案1】:

这是加入命名空间的代码。我没有放入重复行检查器,因为您可能有不同的类可能包含相同的行。不过,像所有 cmets 一样,我认为在一个命名空间中拥有这么多类并不是一个好主意。这就像在一个房子里有500个女人。尽管如此,只需将文件扩展名更改为 .cs,您的 IDE 就会告诉您重复的名称并删除它们。如果您确实找到并编辑了所有符合搜索条件的内容,大约需要 2 分钟。

这里是代码L

 class Program
{
    static void Main(string[] args)
    {
    StreamReader reader;
    StreamWriter writer = new StreamWriter(/*where you want the final txt to be saved. rename the extension to .cs  */);

        string line;
        int count = 0;
        string[] fileEntries = Directory.GetFiles(/*where your cs files are*/");
        foreach (string fileName in fileEntries)
        {
            // do something with fileName

            File.Copy( fileName, /* location to save the now txt .cs files */ + count.ToString() + ".txt");
            count += 1;
        }
        string[] Completetxt = Directory.GetFiles(/*location where you saved the txt files */);

        foreach (string TxtFile in Completetxt)
        {
            reader = new StreamReader(TxtFile);
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
                writer.WriteLine(line);
            }
            reader.Close();
        }


    }
}

请记住,这会将所有 cs 文件复制到一个文件中,其中所有导入以及命名空间名称都在一个文件之下。只需使用您的 IDE 查找副本并删除它们。

祝你好运

【讨论】:

    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    相关资源
    最近更新 更多