|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Linq; |
| 6 | +using System.Reflection; |
| 7 | + |
| 8 | +namespace Microsoft.ClearScript |
| 9 | +{ |
| 10 | + /// <summary> |
| 11 | + /// Represents a custom attribute loader. |
| 12 | + /// </summary> |
| 13 | + public class CustomAttributeLoader |
| 14 | + { |
| 15 | + // ReSharper disable EmptyConstructor |
| 16 | + |
| 17 | + /// <summary> |
| 18 | + /// Initializes a new <see cref="CustomAttributeLoader"/> instance. |
| 19 | + /// </summary> |
| 20 | + public CustomAttributeLoader() |
| 21 | + { |
| 22 | + // the help file builder (SHFB) insists on an empty constructor here |
| 23 | + } |
| 24 | + |
| 25 | + // ReSharper restore EmptyConstructor |
| 26 | + |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Loads custom attributes of the specified type for the given resource. |
| 30 | + /// </summary> |
| 31 | + /// <typeparam name="T">The type, or a base type, of the custom attributes to load.</typeparam> |
| 32 | + /// <param name="resource">The resource for which to load custom attributes of type <typeparamref name="T"/>.</param> |
| 33 | + /// <param name="inherit"><c>True</c> to include custom attributes of type <typeparamref name="T"/> defined for ancestors of <paramref name="resource"/>, <c>false</c> otherwise.</param> |
| 34 | + /// <returns>An array of custom attributes of type <typeparamref name="T"/>.</returns>. |
| 35 | + /// <remarks> |
| 36 | + /// This method is performance-critical. Overrides must not invoke script engine methods or |
| 37 | + /// other ClearScript functionality. The base implementation loads custom attributes via |
| 38 | + /// reflection. |
| 39 | + /// </remarks> |
| 40 | + public virtual T[] LoadCustomAttributes<T>(ICustomAttributeProvider resource, bool inherit) where T : Attribute |
| 41 | + { |
| 42 | + if (resource is MemberInfo member) |
| 43 | + { |
| 44 | + return Attribute.GetCustomAttributes(member, typeof(T), inherit).OfType<T>().ToArray(); |
| 45 | + } |
| 46 | + |
| 47 | + if (resource is ParameterInfo parameter) |
| 48 | + { |
| 49 | + return Attribute.GetCustomAttributes(parameter, typeof(T), inherit).OfType<T>().ToArray(); |
| 50 | + } |
| 51 | + |
| 52 | + if (resource is Assembly assembly) |
| 53 | + { |
| 54 | + return Attribute.GetCustomAttributes(assembly, typeof(T), inherit).OfType<T>().ToArray(); |
| 55 | + } |
| 56 | + |
| 57 | + if (resource is Module module) |
| 58 | + { |
| 59 | + return Attribute.GetCustomAttributes(module, typeof(T), inherit).OfType<T>().ToArray(); |
| 60 | + } |
| 61 | + |
| 62 | + return resource.GetCustomAttributes(typeof(T), inherit).OfType<T>().ToArray(); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments