为什么抛出字符串格式异常

时间:2013-08-19 16:43:39

标签: c# .net

我看不见树木了。

为什么会抛出字符串格式异常?

 private const string GoogleAnalyticsFormat = @"<script type=""text/javascript"">
                                                var _gaq = _gaq || [];

                                                _gaq.push(['_setAccount', '{0}']);
                                                _gaq.push(['_trackPageview']);

                                                (function () {
                                                    var ga = document.createElement('script');
                                                    ga.type = 'text/javascript';
                                                    ga.async = true;
                                                    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                                                    var s = document.getElementsByTagName('script')[0];
                                                    s.parentNode.insertBefore(ga, s);
                                                })();
                                            </script>";

public static IHtmlString RenderGoogleAnalytics<T>(this HtmlHelpers<T> html, string trackingCode )
{
    return html.Raw(string.Format(GoogleAnalyticsFormat, trackingCode));
}

2 个答案:

答案 0 :(得分:10)

查看格式字符串的这一位:

function () { ... }

这些大括号被解释为占位符的开头/结尾。你需要加倍他们:

function () {{ ... }}

所以你的完整声明将是:

private const string GoogleAnalyticsFormat = @"<script type=""text/javascript"">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', '{0}']);
    _gaq.push(['_trackPageview']);
    (function () {{
        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
    }})();
    </script>";

答案 1 :(得分:4)

您必须将大括号{更改为{{