System.Web.HttpUtility.HtmlEncode(Object) 是做什么的?

What does System.Web.HttpUtility.HtmlEncode(Object) do?

the System.Web.HttpUtility.HtmlEncode(Object) overload 到底是做什么的?为什么会有一种方法采用 HTML-encodes 一个 any 类型的对象?考虑到此类操作看起来多么模糊,您会认为文档会提供更多信息...

它做的事情与 HttpUtility.HtmlEncode(String) 做的一样,只是它先将它转换为字符串。

您可以在 reference source

中看到它的确切作用
public static String HtmlEncode(object value) {
    if (value == null) {
        // Return null to be consistent with HtmlEncode(string)
        return null;
    }

    var htmlString = value as IHtmlString;
    if (htmlString != null) {
        return htmlString.ToHtmlString();
    }

    return HtmlEncode(Convert.ToString(value, CultureInfo.CurrentCulture));
}

所以首先它检查对象是否实现 IHtmlString 并调用 ToHtmlString(),如果没有它调用对象上的 Convert.ToString 然后使用 [=15= 的字符串重载] 对转换后的字符串进行 return 结果。