c# - 重构多个 StringBuilder.Append 语句

标签 c# .net refactoring

今天我看到了这个糟糕的代码结构,从那时起我开始认为看到这个具有这段代码的方法真的很尴尬和可怕。代码如下:

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/

相关文章:

.net - 在 EF5 的 select select 子句中选择 null

C++ 帮助重构一个怪物类

c++ - 模板组合和友元传递性

c# - 在C#中创建 “Fake”音频设备?

c# - .NET 4.7.1 项目无法使用 .NET Core 2.0 库

c# - 转换 Jil 动态反序列化对象数组时缺少无参数构造函数

.net - 双击.csproj将打开整个sln,它是

c - 从枚举中删除一个值而不更改其他值

c# - 使用 Agility Pack 用另一个节点包围现有节点

c# - 如何检查 System.Net.WebClient.DownloadData 是否正在下载二进制文件?