分隔符替换方法

时间:2013-03-06 17:33:00

标签: c# asp.net

我想创建一个方法来替换目标使用的分隔符(html电子邮件,日志,数据库)。分隔符是常量,所以我希望能够引用将可识别名称映射到字符串值的对象(semicolon =“;”,htmlLineBreak =“< br />”等)。有没有比这更好的方法呢?

public static class Utilities
{
    public string ReplaceDelimiter(string content
                     , Delimiter currentDelimiter, Delimiter outputDelimiter)
    {
        return content.Replace(currentDelimiter.ToString()
                              , outputDelimiter.ToString());
    }
}

public class Delimiter
{
    public const string comma = ",";
    public const string semicolon = ";";
    public const string colon = ":";
    public const string lineBreak = "\r\n";
    public const string htmlLineBreak = "<br/>";
}

以下评论编辑:
一个用例是当我想将错误记录到不同的目标并在电子邮件中发送相同的内容(格式不同)时。日志可能会转到数据库列(需要带分号分隔符的键/值)或日志文件(希望分隔符是换行符)。电子邮件将是HTML,因此要将分隔符替换为&lt; br /&gt;。

下面是一个日志记录方法的摘录,该方法包含一些参数,包括实际的异常:

StringBuilder delimitedMessage = new StringBuilder();

delimitedMessage.Append("Date=" + DateTime.Now.ToShortDateString() + ";");
delimitedMessage.Append("Time=" + DateTime.Now.ToLongTimeString() + ";");
delimitedMessage.Append("Source=" + objException.Source.ToString().Trim() + ";");
delimitedMessage.Append("Method=" + objException.TargetSite.Name.ToString() + ";");
delimitedMessage.Append("Erring Method=" + methodName + ";");
delimitedMessage.Append("Computer=" + System.Environment.MachineName.ToString() + ";");
delimitedMessage.Append("Log Message=" + logMessage + ";");
delimitedMessage.Append("Exception Error=" + objException.Message.ToString().Trim() + ";");
delimitedMessage.Append("Severity=" + severity.ToString() + ";");
delimitedMessage.Append("Stack Trace=" + objException.StackTrace.ToString().Trim() + ";");

contentToLog = delimitedMessage.ToString();

WriteToDb(contentToLog);
WriteToLog(Utilities.ReplaceDelimiter(contentToLog, Delimiter.semicolon, Delimiter.lineBreak));
SendEmail(Utilities.ReplaceDelimiter(contentToLog, Delimiter.semicolon, Delimiter.htmlLineBreak));

1 个答案:

答案 0 :(得分:1)

  • 代码

    public class Delimiter {
        public static readonly Delimiter
            HtmlLineBreak=new Delimiter {
                Value="<br/>"
            },
            LineBreak=new Delimiter {
                Value="\r\n"
            },
            Semicolon=new Delimiter {
                Value=";"
            },
            Colon=new Delimiter {
                Value=":"
            },
            Comma=new Delimiter {
                Value=","
            };
    
        public override String ToString() {
            return Value;
        }
    
        public String Value {
            get;
            set;
        }
    }
    
  • 测试

    var t=Utilities.ReplaceDelimiter("123\r\n", Delimiter.LineBreak, Delimiter.HtmlLineBreak);
    Debug.Print("{0}", t);
    
  • 输出

      

    123&LT峰; br /&GT;