自动翻译C#文档注释的小程序

在使用visual studio进行代码编写时,它会自动显示代码的文档注释

自动翻译C#文档注释的小程序

很多库的文档注释是英文的,这对像我这样的英文菜鸡来说,降低了编程效率。今晚写了个小程序,配合手工操作,实现了文档注释的翻译,做个分享吧。

static void Export(string file)
{
    StreamWriter writer = new StreamWriter(file + ".txt");
    XmlDocument doc = new XmlDocument();
    doc.Load(file + ".xml");
    var members = doc.SelectSingleNode("doc/members");
    char[] splitor = { ' ' };
    Process = (node) => {
        bool isFirstLine = true;
        foreach (var line in node.Value.Split(splitor, StringSplitOptions.RemoveEmptyEntries))
        {
            if (string.IsNullOrWhiteSpace(line)) continue;
            if (isFirstLine)
                isFirstLine = false;
            else
                writer.Write(' ');
            writer.Write(line.Trim());
        }
        writer.WriteLine();
    };
    EachElement(members);
    writer.Close();
}
static  Action<XmlNode> Process;
static void EachElement(XmlNode node)
{
    if (node.NodeType == XmlNodeType.Text)
    {
        Process(node);
    }
    else
    {
        foreach (XmlNode item in node.ChildNodes)
        {
            EachElement(item);
        }
    }
}

static void Import(string file)
{
    StreamReader txt = new StreamReader(file + ".txt");
    XmlDocument doc = new XmlDocument();
    doc.Load(file + ".xml");
    var members = doc.SelectSingleNode("doc/members");
    Process = (node) => {
        node.Value = txt.ReadLine();
    };
    EachElement(members);
    doc.Save(file + "2.xml");
}

比如我有一个MathNet.Numerics.xml的注释文件,那我调用Export("MathNet.Spatial")将会在该目录下生成MathNet.Spatial.txt文件。

自动翻译C#文档注释的小程序

将MathNet.Spatial.txt用Chrome浏览器打开

自动翻译C#文档注释的小程序

右键,翻译成中文。把中文注释复制出来,覆盖掉原来MathNet.Spatial.txt中的内容。然后调用Import("MathNet.Spatial"),该操作会在同级目录下创建MathNet.Spatial2.xml,它就是我们需要的中文注释。

自动翻译C#文档注释的小程序

接下来怎么做,你懂得!