2012-12-11 207 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]); 

這是假設你要搜尋字符串要被格式化的替換字符串。

相關問題