4

HtmlTextWriter用来将 html 输出到流中。但是,我缺少一种编写 html 注释的方法。当然,我可以写一个扩展方法

public static void WriteComment(this HtmlTextWriter writer, string comment)
{
  writer.Write("<!-- ");
  writer.WriteEncodedText(comment);
  writer.Write(" -->");
}

但这确实感觉有点不雅 - 是否有一些我没有看到的内置方法?

4

1 回答 1

2

在检查规范之后,我可以争辩说这些扩展可能更正确,

public static void WriteBeginComment(this HtmlTextWriter writer)
{
    writer.Write(HtmlTextWriter.TagLeftChar);
    writer.Write("!--");
}

public static void WriteEndComment(this HtmlTextWriter writer)
{
    writer.Write("--");
    writer.Write(HtmlTextWriter.TagRightChar);
}

public static void WriteComment(this HtmlTextWriter writer, string comment)
{
    if (
        comment.StartsWith(">") || 
        comment.StartsWith("->") || 
        comment.Contains("--") ||
        comment.EndsWith("-"))
    {
        throw new ArgumentException(
            "text does not meet HTML5 specification",
            "comment");
    }

    writer.WriteBeginComment();
    writer.Write(comment);
    writer.WriteEndComment();
}
于 2013-02-07T11:01:09.007 回答