-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathCustomAttributeLoader.cs
More file actions
76 lines (64 loc) · 2.91 KB
/
CustomAttributeLoader.cs
File metadata and controls
76 lines (64 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Linq;
using System.Reflection;
namespace Microsoft.ClearScript
{
/// <summary>
/// Represents a custom attribute loader.
/// </summary>
public class CustomAttributeLoader
{
private readonly CustomAttributeCache cache = new();
// ReSharper disable EmptyConstructor
/// <summary>
/// Initializes a new <c><see cref="CustomAttributeLoader"/></c> instance.
/// </summary>
public CustomAttributeLoader()
{
// the help file builder (SHFB) insists on an empty constructor here
}
/// <summary>
/// Gets the default custom attribute loader.
/// </summary>
public static CustomAttributeLoader Default { get; } = new();
// ReSharper restore EmptyConstructor
/// <summary>
/// Loads custom attributes of the specified type for the given resource.
/// </summary>
/// <typeparam name="T">The type, or a base type, of the custom attributes to load.</typeparam>
/// <param name="resource">The resource for which to load custom attributes of type <typeparamref name="T"/>.</param>
/// <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>
/// <returns>An array of custom attributes of type <typeparamref name="T"/>.</returns>.
/// <remarks>
/// This method is performance-critical. Overrides must not invoke script engine methods or
/// other ClearScript functionality. The base implementation loads custom attributes via
/// reflection.
/// </remarks>
public virtual T[] LoadCustomAttributes<T>(ICustomAttributeProvider resource, bool inherit) where T : Attribute
{
if (resource is MemberInfo member)
{
return Attribute.GetCustomAttributes(member, typeof(T), inherit).OfType<T>().ToArray();
}
if (resource is ParameterInfo parameter)
{
return Attribute.GetCustomAttributes(parameter, typeof(T), inherit).OfType<T>().ToArray();
}
if (resource is Assembly assembly)
{
return Attribute.GetCustomAttributes(assembly, typeof(T), inherit).OfType<T>().ToArray();
}
if (resource is Module module)
{
return Attribute.GetCustomAttributes(module, typeof(T), inherit).OfType<T>().ToArray();
}
return resource.GetCustomAttributes(typeof(T), inherit).OfType<T>().ToArray();
}
internal T[] GetOrLoad<T>(ICustomAttributeProvider resource, bool inherit) where T : Attribute
{
return cache.GetOrLoad<T>(this, resource, inherit);
}
}
}