分隔符替换方法

本文关键字:方法 替换 分隔符 | 更新日期: 2023-09-27 18:02:31

我想创建一个方法来替换分隔符的预期目标用途(html电子邮件,日志,数据库)。分隔符是常量,所以我希望能够引用一个对象,将可识别的名称映射到字符串值(分号= ";",htmlLineBreak = "
"等)。有没有比下面的方法更好的方法?

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,所以希望分隔符替换为

下面是一个日志方法的摘录,它有几个参数,包括实际的Exception:

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));

分隔符替换方法

  • 代码
    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/祝辞