feat: Added ToStringUndefined method to EnumUtils for printing known flags of an undefined composite

This commit is contained in:
Chris Cameron
2020-12-01 16:53:45 -05:00
parent 81d1a97304
commit 3381977050
3 changed files with 60 additions and 1 deletions

View File

@@ -290,5 +290,17 @@ namespace ICD.Common.Utils.Tests
}
#endregion
#region Formatting
[TestCase(eTestFlagsEnum.A | eTestFlagsEnum.B | eTestFlagsEnum.C | (eTestFlagsEnum)8,
"A, B, C, 8")]
public void ToStringUndefinedTest(eTestFlagsEnum value, string expected)
{
string toString = EnumUtils.ToStringUndefined(value);
Assert.AreEqual(expected, toString);
}
#endregion
}
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICD.Common.Properties;
using ICD.Common.Utils.Extensions;
#if SIMPLSHARP
@@ -756,5 +757,39 @@ namespace ICD.Common.Utils
}
#endregion
#region Formatting
/// <summary>
/// Builds a comma delimited string of the defined enum flags, followed by the numeric remainder.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static string ToStringUndefined<T>(T value)
where T : struct, IConvertible
{
if (!IsFlagsEnum<T>())
return value.ToString();
long remainder = (int)(object)value;
StringBuilder output = new StringBuilder();
string format = "{0}";
foreach (T flag in GetFlagsExceptNone(value))
{
output.AppendFormat(format, flag);
remainder -= (int)(object)flag;
format = ", {0}";
}
if (remainder != 0)
output.AppendFormat(", {0}", remainder);
return output.ToString();
}
#endregion
}
}

View File

@@ -60,7 +60,7 @@ namespace ICD.Common.Utils.Extensions
}
/// <summary>
/// Returns the enum value as a
/// Returns the enum value as a ushort.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
@@ -71,5 +71,17 @@ namespace ICD.Common.Utils.Extensions
{
return (ushort)(object)extends;
}
/// <summary>
/// Builds a comma delimited string of the defined enum flags, followed by the numeric remainder.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
/// <returns></returns>
public static string ToStringUndefined<T>(this T extends)
where T : struct, IConvertible
{
return EnumUtils.ToStringUndefined(extends);
}
}
}