I would just cache the result, since type attributes will not change.
public class SomeHelperClass
{
private static readonly ConcurrentDictionary<Type, bool> messageAttributesCache = new ConcurrentDictionary<Type, bool>();
private static readonly Type messageAttributeType = typeof(MessageAttribute);
public static bool IsMessageAttributeDefined(Type type)
{
bool isDefined = false;
if (messageAttributesCache.TryGetValue(type, out isDefined))
{
return isDefined;
}
isDefined = type.IsDefined(messageAttributeType, false);
return messageAttributesCache[type] = isDefined;
}
}
Then use
bool isDefined = SomeHelperClass.IsMessageAttributeDefined(type);
You can make the solution general, I just give some idea, this is some kind of quick ugly code. However, it will be better.
source
share