Skip to content

Instantly share code, notes, and snippets.

@virtualstaticvoid
Last active May 31, 2018 10:49
Show Gist options
  • Save virtualstaticvoid/105255 to your computer and use it in GitHub Desktop.
Save virtualstaticvoid/105255 to your computer and use it in GitHub Desktop.
Attribute reflection support
//
// MIT License
// Copyright (c) 2009 Chris Stefano <virtualstaticvoid@gmail.com>
// 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