Last active
May 31, 2018 10:49
-
-
Save virtualstaticvoid/105255 to your computer and use it in GitHub Desktop.
Attribute reflection support
This file contains hidden or 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
// | |
// MIT License | |
// Copyright (c) 2009 Chris Stefano <[email protected]> | |
// https://gist.github.com/virtualstaticvoid/105255 | |
// | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
public static class AttributeSupport | |
{ | |
public static T GetAttribute<T>(this object instance) | |
where T : Attribute | |
{ | |
return instance.GetType().GetAttribute<T>(/* inherit */ true); | |
} | |
public static T GetAttribute<T>(this ICustomAttributeProvider provider) | |
where T : Attribute | |
{ | |
return provider.GetAttribute<T>(/* inherit */ true); | |
} | |
public static T GetAttribute<T>(this ICustomAttributeProvider provider, bool inherit) | |
where T : Attribute | |
{ | |
var attributes = provider.GetCustomAttributes(typeof(T), inherit); | |
return attributes.Length > 0 ? attributes[0] as T : null; | |
} | |
public static T[] GetAttributes<T>(this ICustomAttributeProvider provider) | |
where T : Attribute | |
{ | |
return provider.GetAttributes<T>(/* inherit */ true); | |
} | |
public static T[] GetAttributes<T>(this ICustomAttributeProvider provider, bool inherit) | |
where T : Attribute | |
{ | |
var attributes = provider.GetCustomAttributes(typeof(T), inherit); | |
return attributes.Select(attr => attr as T).ToArray(); | |
} | |
public static void ForAttributesOf<T>(this ICustomAttributeProvider provider, Action<T> action) | |
where T : Attribute | |
{ | |
provider.ForAttributesOf<T>(/* inherit */ true, action); | |
} | |
public static void ForAttributesOf<T>(this ICustomAttributeProvider provider, bool inherit, Action<T> action) | |
where T : Attribute | |
{ | |
foreach (T attribute in provider.GetCustomAttributes(typeof(T), inherit)) | |
{ | |
action(attribute); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment