今天我看到了这个糟糕的代码结构,从那时起我开始认为看到这个具有这段代码的方法真的很尴尬和可怕。代码如下:
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);
关于c# - 重构多个 StringBuilder.Append 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7926974/