0

我正在尝试构建一个电子邮件模板。我得到了假设的工作示例,但我在尝试让 FormatWith() 解决其中一个函数时遇到问题。

private static string PrepareMailBodyWith(string templateName, params string[] pairs)
{
    string body = GetMailBodyOfTemplate(templateName);

    for (var i = 0; i < pairs.Length; i += 2)
    {
        // wonder if I can bypass Format with and just use String.Format
        body = body.Replace("<%={0}%>".FormatWith(pairs[i]), pairs[i + 1]);
        //body = body.Replace("<%={0}%>",String.Format(pairs[i]), pairs[i + 1]);
    }
    return body;
}
4

3 回答 3

1

对我来说,它看起来像是一种扩展方法

您需要引用扩展方法位于文件顶部的命名空间。

例子:

namespace MyApp.ExtensionMethods
{
    public class MyExtensions
    {    
        public static string FormatWith(this string target, params object[] args) 
        { 
            return string.Format(Constants.CurrentCulture, target, args); 
        }    
    }
}

...

using MyApp.ExtensionMethods;

...

private static string PrepareMailBodyWith(string templateName, params string[] pairs)
{
    string body = GetMailBodyOfTemplate(templateName);

    for (var i = 0; i < pairs.Length; i += 2)
    {
        // wonder if I can bypass Format with and just use String.Format
        body = body.Replace("<%={0}%>".FormatWith(pairs[i]), pairs[i + 1]);
        //body = body.Replace("<%={0}%>",String.Format(pairs[i]), pairs[i + 1]);
    }
    return body;
}
于 2012-12-11T22:44:41.900 回答
0

我发现使用 .Replace() 然后跳过所有其他的箍更容易。谢谢你的建议。

        string email = emailTemplate
        .Replace("##USERNAME##", userName)
        .Replace("##MYNAME##", myName);

这似乎是我的电子邮件模板问题的最简单解决方案。

于 2012-12-12T14:05:12.743 回答
0

Try using String.Format() instead, like you suggested...

body = body.Replace(String.Format("<%={0}%>", pairs[i]), String.Format("<%={0}%>", pairs[i+1]);

This assumes you want both the search string and the replacement string to be formatted.

于 2012-12-11T22:54:39.443 回答