/
SwitchAttribute.cs
90 lines (76 loc) · 3.09 KB
/
SwitchAttribute.cs
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace System.Diagnostics
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Constructor |
AttributeTargets.Event | AttributeTargets.Method | AttributeTargets.Property)]
public sealed class SwitchAttribute : Attribute
{
private Type _type;
private string _name;
public SwitchAttribute(string switchName, Type switchType)
{
SwitchName = switchName;
SwitchType = switchType;
}
public string SwitchName
{
get { return _name; }
[MemberNotNull(nameof(_name))]
set
{
ArgumentException.ThrowIfNullOrEmpty(value);
_name = value;
}
}
public Type SwitchType
{
get { return _type; }
[MemberNotNull(nameof(_type))]
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_type = value;
}
}
public string? SwitchDescription { get; set; }
[RequiresUnreferencedCode("Types may be trimmed from the assembly.")]
public static SwitchAttribute[] GetAll(Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException(nameof(assembly));
List<object> switchAttribs = new List<object>();
object[] attribs = assembly.GetCustomAttributes(typeof(SwitchAttribute), false);
switchAttribs.AddRange(attribs);
foreach (Type type in assembly.GetTypes())
{
GetAllRecursive(type, switchAttribs);
}
SwitchAttribute[] ret = new SwitchAttribute[switchAttribs.Count];
switchAttribs.CopyTo(ret, 0);
return ret;
}
private static void GetAllRecursive([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, List<object> switchAttribs)
{
GetAllRecursive((MemberInfo)type, switchAttribs);
MemberInfo[] members = type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.DeclaredOnly | BindingFlags.Instance |
BindingFlags.Static);
foreach (MemberInfo member in members)
{
// ignore Types here. They will get covered by the top level assembly.GetTypes
if (!(member is Type))
GetAllRecursive(member, switchAttribs);
}
}
private static void GetAllRecursive(MemberInfo member, List<object> switchAttribs)
{
object[] attribs = member.GetCustomAttributes(typeof(SwitchAttribute), false);
switchAttribs.AddRange(attribs);
}
}
}