重构多个StringBuilder.附加声明
本文关键字:声明 StringBuilder 重构 | 更新日期: 2023-09-27 18:12:43
今天我看到了这个糟糕的代码结构,从那时起我开始认为看到这个方法有这样的代码真的很尴尬和可怕。代码是这样的:
StringBuilder body = new StringBuilder();
#region General
body.Append("General information:");
body.Append('*');
body.Append('*');
body.Append("Exception: ");
body.Append(m_ExceptionInfo.Exception.GetType().ToString());
body.Append('*');
body.Append("Message: ");
body.Append(m_ExceptionInfo.Exception.Message);
body.Append('*');
body.Append("Method: ");
body.Append(m_ExceptionInfo.GetMethodName(m_ExceptionInfo.Exception));
body.Append('*');
body.Append("Class: ");
body.Append(m_ExceptionInfo.GetClassName(m_ExceptionInfo.Exception));
body.Append('*');
body.Append("Assembly: ");
body.Append(m_ExceptionInfo.AssemblyName);
body.Append('*');
body.Append("App-Domain: ");
body.Append(m_ExceptionInfo.AppDomainName);
body.Append('*');
body.Append("Source-File: ");
body.Append(m_ExceptionInfo.GetFileName(m_ExceptionInfo.Exception));
body.Append('*');
body.Append("Line/Row: ");
body.Append(
m_ExceptionInfo.GetFileLineNumber(m_ExceptionInfo.Exception).ToString(currentNumberFormatInfoProvider));
我们这样做是为了定制UI中显示的错误消息框信息。因此我们准备了一个有这么多信息的字符串。但对我来说,看着这些代码却不知道如何重构它,感觉很糟糕。
任何帮助都是感激的!由于
使用StringBuilder.AppendFormat()方法:
StringBuilder body = new StringBuilder();
body.AppendFormat("Exception: {0}, Message: {1}{2}Class: {3}, Assembly: {4}{5}",
m_ExceptionInfo.Exception.GetType(),
m_ExceptionInfo.Exception.Message,
Environment.NewLine,
m_ExceptionInfo.GetClassName(...),
m_ExceptionInfo.AssemblyName,
Environment.NewLine);
body.AppendFormat("App-Domain: {0}, Source-File: {1}{2}",
m_ExceptionInfo.AppDomainName,
m_ExceptionInfo.GetFileName(...),
Environment.NewLine);
为什么不创建一个简单的字符串对集合,然后遍历它们来构建实际的字符串呢?如:
Dictionary<string, string> info = new Dictionary<string, string>();
info.Add("General information", "*");
info.Add("Exception", m_ExceptionInfo.Exception.GetType().ToString());
info.Add("Message", m_ExceptionInfo.Exception.Message);
//etc
StringBuilder body = new StringBuilder();
foreach(KeyValuePair<string, string> stringPair in info)
body.AppendFormat("{0}:{1, 20}", stringPair.Key, stringPair.Value);
为添加的每个信息位创建具有有意义的名称的单独方法将使该方法看起来更好:
private void AppendExceptionMessage(StringBuilder builder)
{
builder.Append("Message: ");
builder.Append(m_ExceptionInfo.Exception.Message);
builder.Append('*');
}
private void AppendMethodInfo(StringBuilder builder)
{
builder.Append("Method: ");
builder.Append(m_ExceptionInfo.GetMethodName(m_ExceptionInfo.Exception));
builder.Append('*');
}
body.Append("General information:");
body.Append('*');
body.Append('*');
AppendExceptionMessage(body);
AppendMethodInfo(body);