Created
October 13, 2017 23:17
-
-
Save jaymedavis/b1d773064d860dec0408fffe2ed30a5b to your computer and use it in GitHub Desktop.
Reading the StripeBilling Attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @jaymedavis! I gave this a try, however it seems I cannot call
GetCustomAttributes
becausepropertyValue
has been downcast to anobject
in the parser function:Any idea how I could fix that? It's probably simple but I can't seem to figure it out...