Initial commit of ReprBuilder

This commit is contained in:
Chris Cameron
2017-09-08 16:44:04 -04:00
parent 03b43e38d7
commit b48525949e
2 changed files with 83 additions and 0 deletions

View File

@@ -87,6 +87,7 @@
<Compile Include="Extensions\ListExtensions.cs" />
<Compile Include="Properties\Annotations.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ReprBuilder.cs" />
<Compile Include="Services\Logging\ILoggerService.cs" />
<Compile Include="Services\Logging\LogItem.cs" />
<Compile Include="Services\Logging\LogItemEventArgs.cs" />

View File

@@ -0,0 +1,82 @@
using System.Collections.Generic;
using System.Text;
namespace ICD.Common.Utils
{
/// <summary>
/// Simple class for building a string representation of an object.
/// </summary>
public sealed class ReprBuilder
{
private readonly object m_Instance;
private readonly List<string> m_PropertyOrder;
private readonly Dictionary<string, object> m_PropertyValues;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="instance"></param>
public ReprBuilder(object instance)
{
m_Instance = instance;
m_PropertyOrder = new List<string>();
m_PropertyValues = new Dictionary<string, object>();
}
/// <summary>
/// Adds the property with the given name and value to the
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void AppendProperty(string name, object value)
{
m_PropertyOrder.Remove(name);
m_PropertyOrder.Add(name);
m_PropertyValues[name] = value;
}
/// <summary>
/// Returns the result of the builder.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (m_Instance == null)
return GetValueStringRepresentation(m_Instance);
StringBuilder builder = new StringBuilder();
builder.Append(m_Instance.GetType().Name);
builder.Append('(');
for (int index = 0; index < m_PropertyOrder.Count; index++)
{
string property = m_PropertyOrder[index];
builder.Append(property);
builder.Append('=');
object value = m_PropertyValues[property];
string valueString = GetValueStringRepresentation(value);
builder.Append(valueString);
if (index < m_PropertyOrder.Count - 1)
builder.Append(", ");
}
builder.Append(')');
return builder.ToString();
}
private static string GetValueStringRepresentation(object value)
{
if (value == null || value is string)
return StringUtils.ToRepresentation(value as string);
return value.ToString();
}
}
}