using System; | |
using System.Linq; | |
using System.Reflection; | |
using System.Runtime.Serialization; | |
namespace SmoothNumerator | |
{ | |
class Program | |
{ | |
public enum StripeBilling | |
{ | |
[EnumMember(Value = "charge_automatically")] | |
ChargeAutomatically, | |
[EnumMember(Value = "send_invoice")] | |
SendInvoice, | |
} | |
public class SomeStripeEntity | |
{ | |
public StripeBilling Billing { get; set; } | |
} | |
static void Main(string[] args) | |
{ | |
var foo = new SomeStripeEntity | |
{ | |
Billing = StripeBilling.ChargeAutomatically | |
}; | |
// passed to the middleware Parse() as the `property` argument | |
var property = foo.Billing.GetType().GetProperty(nameof(StripeBilling)); | |
// passed to the middleware Parse() as the 'propertyValue' argument | |
var propertyValue = foo.Billing.GetType().GetField(foo.Billing.ToString()); | |
// grab the attributes from the property (line 20, you know it's an enum already) | |
var attributes = propertyValue.GetCustomAttributes(false); | |
// if it has a value attribute, read it | |
dynamic attribute = attributes.ElementAt(0); | |
Console.WriteLine(attribute?.Value ?? "I couldn't find that!"); | |
//// outputs: charge_automatically | |
// keep the terminal open | |
Console.ReadLine(); | |
} | |
} | |
} |
Thanks @jaymedavis! I gave this a try, however it seems I cannot call GetCustomAttributes
because propertyValue
has been downcast to an object
in the parser function:
error CS1929: 'object' does not contain a definition for 'GetCustomAttributes' and the best extension method overload 'CustomAttributeExtensions.GetCustomAttributes(Assembly, Type)' requires a receiver of type 'Assembly'
Any idea how I could fix that? It's probably simple but I can't seem to figure it out...
propertyValue.GetType() maybe?
Also could try...
typeof(propertyValue).GetTypeInfo().GetCustomAttribute<>() ....
might work too.
You might be able to create a base type for all StripeEnums called StripeEnum. Then, all your enums could inherit from there. That way, the last example could become .GetCustomAttribute<StripeEnum>
to avoid potential problems in the case of having more than one attribute on the property.
The System.Linq reference isn’t needed here, unless you want to try attributes.Any(), to be on the defensive side.