2012-12-11 203 views
0

我想建立一个电子邮件模板。我得到了什么是假设的工作示例,但我在尝试获取FormatWith()以解决其中一个函数时出现问题。我想使用一个函数,使用FormatWith(),我得到一个错误在C#

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; 
} 
+0

我已经包括所有这些NameSpaces试图解决它。 'using System;使用System.IO的 ; using System.Collections.Generic;使用System.Linq的 ; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net.Mail; using System.Net.Mime; using System.Web.Configuration; using System.Net.Configuration; using System.Configuration;使用System.Globalization的 ; using System.String;使用System.IFormatProvider的 ;使用System.Object;' – user1830640

回答

0

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

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

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

1

对我来说,它看起来像一个extension method

您需要引用命名空间的扩展方法住在你的文件的顶部。

例子:

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; 
} 
+0

我已经在使用这个'public static string FormatWith(this string target,params object [] args) {0}返回string.Format(Constants.CurrentCulture,target,args); }”我从代码[链接](http://www.waytocoding.com/2011/02/how-to-send-email-with-prepared.html) – user1830640

+0

即扩展方法住在一个名称空间,然后。您只需在文件顶部添加引用该命名空间的'using'语句即可。 – Khan

+0

试过,说NameSpace找不到我添加了我从这个例子中得到的链接。 [示例代码](http://www.waytocoding.com/2011/02/how-to-send-email-with-prepared.html) – user1830640

0

尝试使用String.Format()相反,像你的建议...

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

这是假设你要搜寻字符串要被格式化的替换字符串。

相关问题