Browse Source

Add StringValue GetValues helper

pull/438/head
Ionite 10 months ago
parent
commit
a35c1f37a9
No known key found for this signature in database
  1. 32
      StabilityMatrix.Core/Models/StringValue.cs

32
StabilityMatrix.Core/Models/StringValue.cs

@ -1,4 +1,8 @@
namespace StabilityMatrix.Core.Models;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.Serialization;
namespace StabilityMatrix.Core.Models;
public abstract record StringValue(string Value) : IFormattable
{
@ -13,4 +17,30 @@ public abstract record StringValue(string Value) : IFormattable
{
return Value;
}
/// <summary>
/// Get all values of type <typeparamref name="T"/> as a dictionary.
/// Includes all public static properties.
/// </summary>
protected static Dictionary<string, T> GetValues<
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T
>()
where T : StringValue
{
var values = new Dictionary<string, T>();
foreach (var field in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Static))
{
if (field.GetValue(null) is T value)
{
// Exclude if IgnoreDataMember
if (field.GetCustomAttribute<IgnoreDataMemberAttribute>() is not null)
continue;
values.Add(value.Value, value);
}
}
return values;
}
}

Loading…
Cancel
Save