-
Notifications
You must be signed in to change notification settings - Fork 82
/
ReflectionUtils.cs
1491 lines (1214 loc) · 62 KB
/
ReflectionUtils.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_METADATA_READER
using Microsoft.Scripting.Metadata;
#endif
using TypeInfo = System.Type;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
namespace Microsoft.Scripting.Utils {
public static class ReflectionUtils {
#region Accessibility
public static BindingFlags AllMembers = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
public static bool IsPublic(this PropertyInfo property) {
return property.GetGetMethod(nonPublic: false) != null
|| property.GetSetMethod(nonPublic: false) != null;
}
public static bool IsStatic(this PropertyInfo property) {
var getter = property.GetGetMethod(nonPublic: true);
var setter = property.GetSetMethod(nonPublic: true);
return getter != null && getter.IsStatic
|| setter != null && setter.IsStatic;
}
public static bool IsStatic(this EventInfo evnt) {
var add = evnt.GetAddMethod(nonPublic: true);
var remove = evnt.GetRemoveMethod(nonPublic: true);
return add != null && add.IsStatic
|| remove != null && remove.IsStatic;
}
public static bool IsPrivate(this PropertyInfo property) {
var getter = property.GetGetMethod(nonPublic: true);
var setter = property.GetSetMethod(nonPublic: true);
return (getter == null || getter.IsPrivate)
&& (setter == null || setter.IsPrivate);
}
public static bool IsPrivate(this EventInfo evnt) {
var add = evnt.GetAddMethod(nonPublic: true);
var remove = evnt.GetRemoveMethod(nonPublic: true);
return (add == null || add.IsPrivate)
&& (remove == null || remove.IsPrivate);
}
private static bool MatchesFlags(ConstructorInfo member, BindingFlags flags) {
return
((member.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
((member.IsStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
}
private static bool MatchesFlags(MethodInfo member, BindingFlags flags) {
return
((member.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
((member.IsStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
}
private static bool MatchesFlags(FieldInfo member, BindingFlags flags) {
return
((member.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
((member.IsStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
}
private static bool MatchesFlags(PropertyInfo member, BindingFlags flags) {
return
((member.IsPublic() ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
((member.IsStatic() ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
}
private static bool MatchesFlags(EventInfo member, BindingFlags flags) {
var add = member.GetAddMethod();
var remove = member.GetRemoveMethod();
var raise = member.GetRaiseMethod();
bool isPublic = add != null && add.IsPublic || remove != null && remove.IsPublic || raise != null && raise.IsPublic;
bool isStatic = add != null && add.IsStatic || remove != null && remove.IsStatic || raise != null && raise.IsStatic;
return
((isPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
((isStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
}
private static bool MatchesFlags(TypeInfo member, BindingFlags flags) {
// Static/Instance are ignored
return (((member.IsPublic || member.IsNestedPublic) ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0;
}
private static bool MatchesFlags(MemberInfo member, BindingFlags flags) {
ConstructorInfo ctor;
MethodInfo method;
FieldInfo field;
EventInfo evnt;
PropertyInfo property;
if ((method = member as MethodInfo) != null) {
return MatchesFlags(method, flags);
}
if ((field = member as FieldInfo) != null) {
return MatchesFlags(field, flags);
}
if ((ctor = member as ConstructorInfo) != null) {
return MatchesFlags(ctor, flags);
}
if ((evnt = member as EventInfo) != null) {
return MatchesFlags(evnt, flags);
}
if ((property = member as PropertyInfo) != null) {
return MatchesFlags(property, flags);
}
return MatchesFlags((TypeInfo)member, flags);
}
private static IEnumerable<T> WithBindingFlags<T>(this IEnumerable<T> members, Func<T, BindingFlags, bool> matchFlags, BindingFlags flags)
where T : MemberInfo {
return members.Where(member => matchFlags(member, flags));
}
public static IEnumerable<MemberInfo> WithBindingFlags(this IEnumerable<MemberInfo> members, BindingFlags flags) {
return members.WithBindingFlags(MatchesFlags, flags);
}
public static IEnumerable<MethodInfo> WithBindingFlags(this IEnumerable<MethodInfo> members, BindingFlags flags) {
return members.WithBindingFlags(MatchesFlags, flags);
}
public static IEnumerable<ConstructorInfo> WithBindingFlags(this IEnumerable<ConstructorInfo> members, BindingFlags flags) {
return members.WithBindingFlags(MatchesFlags, flags);
}
public static IEnumerable<FieldInfo> WithBindingFlags(this IEnumerable<FieldInfo> members, BindingFlags flags) {
return members.WithBindingFlags(MatchesFlags, flags);
}
public static IEnumerable<PropertyInfo> WithBindingFlags(this IEnumerable<PropertyInfo> members, BindingFlags flags) {
return members.WithBindingFlags(MatchesFlags, flags);
}
public static IEnumerable<EventInfo> WithBindingFlags(this IEnumerable<EventInfo> members, BindingFlags flags) {
return members.WithBindingFlags(MatchesFlags, flags);
}
public static IEnumerable<TypeInfo> WithBindingFlags(this IEnumerable<TypeInfo> members, BindingFlags flags) {
return members.WithBindingFlags(MatchesFlags, flags);
}
public static MemberInfo WithBindingFlags(this MemberInfo member, BindingFlags flags) {
return member != null && MatchesFlags(member, flags) ? member : null;
}
public static MethodInfo WithBindingFlags(this MethodInfo member, BindingFlags flags) {
return member != null && MatchesFlags(member, flags) ? member : null;
}
public static ConstructorInfo WithBindingFlags(this ConstructorInfo member, BindingFlags flags) {
return member != null && MatchesFlags(member, flags) ? member : null;
}
public static FieldInfo WithBindingFlags(this FieldInfo member, BindingFlags flags) {
return member != null && MatchesFlags(member, flags) ? member : null;
}
public static PropertyInfo WithBindingFlags(this PropertyInfo member, BindingFlags flags) {
return member != null && MatchesFlags(member, flags) ? member : null;
}
public static EventInfo WithBindingFlags(this EventInfo member, BindingFlags flags) {
return member != null && MatchesFlags(member, flags) ? member : null;
}
public static TypeInfo WithBindingFlags(this TypeInfo member, BindingFlags flags) {
return member != null && MatchesFlags(member, flags) ? member : null;
}
#endregion
#region Signatures
public static IEnumerable<MethodInfo> WithSignature(this IEnumerable<MethodInfo> members, Type[] parameterTypes) {
return members.Where(c => {
var ps = c.GetParameters();
if (ps.Length != parameterTypes.Length) {
return false;
}
for (int i = 0; i < ps.Length; i++) {
if (parameterTypes[i] != ps[i].ParameterType) {
return false;
}
}
return true;
});
}
public static IEnumerable<ConstructorInfo> WithSignature(this IEnumerable<ConstructorInfo> members, Type[] parameterTypes) {
return members.Where(c => {
var ps = c.GetParameters();
if (ps.Length != parameterTypes.Length) {
return false;
}
for (int i = 0; i < ps.Length; i++) {
if (parameterTypes[i] != ps[i].ParameterType) {
return false;
}
}
return true;
});
}
#endregion
#region Member Inheritance
// CLI specification, partition I, 8.10.4: Hiding, overriding, and layout
// ----------------------------------------------------------------------
// While hiding applies to all members of a type, overriding deals with object layout and is applicable only to instance fields
// and virtual methods. The CTS provides two forms of member overriding, new slot and expect existing slot. A member of a derived
// type that is marked as a new slot will always get a new slot in the objects layout, guaranteeing that the base field or method
// is available in the object by using a qualified reference that combines the name of the base type with the name of the member
// and its type or signature. A member of a derived type that is marked as expect existing slot will re-use (i.e., share or override)
// a slot that corresponds to a member of the same kind (field or method), name, and type if one already exists from the base type;
// if no such slot exists, a new slot is allocated and used.
//
// The general algorithm that is used for determining the names in a type and the layout of objects of the type is roughly as follows:
// - Flatten the inherited names (using the hide by name or hide by name-and-signature rule) ignoring accessibility rules.
// - For each new member that is marked expect existing slot, look to see if an exact match on kind (i.e., field or method),
// name, and signature exists and use that slot if it is found, otherwise allocate a new slot.
// - After doing this for all new members, add these new member-kind/name/signatures to the list of members of this type
// - Finally, remove any inherited names that match the new members based on the hide by name or hide by name-and-signature rules.
// NOTE: Following GetXxx only implement overriding, not hiding specified by hide-by-name or hide-by-name-and-signature flags.
public static IEnumerable<MethodInfo> GetInheritedMethods(this Type type, string name = null, bool flattenHierarchy = false) {
while (type.IsGenericParameter) {
type = type.GetBaseType();
}
var baseDefinitions = new HashSet<MethodInfo>(ReferenceEqualityComparer<MethodInfo>.Instance);
foreach (var ancestor in type.Ancestors()) {
foreach (var declaredMethod in ancestor.GetDeclaredMethods(name)) {
if (declaredMethod != null && IncludeMethod(declaredMethod, type, baseDefinitions, flattenHierarchy)) {
yield return declaredMethod;
}
}
}
}
private static bool IncludeMethod(MethodInfo member, Type reflectedType, HashSet<MethodInfo> baseDefinitions, bool flattenHierarchy) {
if (member.IsVirtual) {
if (baseDefinitions.Add(RuntimeReflectionExtensions.GetRuntimeBaseDefinition(member))) {
return true;
}
} else if (member.DeclaringType == reflectedType) {
return true;
} else if (!member.IsPrivate && (!member.IsStatic || flattenHierarchy)) {
return true;
}
return false;
}
public static IEnumerable<PropertyInfo> GetInheritedProperties(this Type type, string name = null, bool flattenHierarchy = false) {
while (type.IsGenericParameter) {
type = type.GetBaseType();
}
var baseDefinitions = new HashSet<MethodInfo>(ReferenceEqualityComparer<MethodInfo>.Instance);
foreach (var ancestor in type.Ancestors()) {
if (name != null) {
var declaredProperty = ancestor.GetDeclaredProperty(name);
if (declaredProperty != null && IncludeProperty(declaredProperty, type, baseDefinitions, flattenHierarchy)) {
yield return declaredProperty;
}
} else {
foreach (var declaredProperty in ancestor.GetDeclaredProperties()) {
if (IncludeProperty(declaredProperty, type, baseDefinitions, flattenHierarchy)) {
yield return declaredProperty;
}
}
}
}
}
// CLI spec 22.34 Properties
// -------------------------
// [Note: The CLS (see Partition I) refers to instance, virtual, and static properties.
// The signature of a property (from the Type column) can be used to distinguish a static property,
// since instance and virtual properties will have the HASTHIS bit set in the signature (§23.2.1)
// while a static property will not. The distinction between an instance and a virtual property
// depends on the signature of the getter and setter methods, which the CLS requires to be either
// both virtual or both instance. end note]
private static bool IncludeProperty(PropertyInfo member, Type reflectedType, HashSet<MethodInfo> baseDefinitions, bool flattenHierarchy) {
var getter = member.GetGetMethod(nonPublic: true);
var setter = member.GetSetMethod(nonPublic: true);
MethodInfo virtualAccessor;
if (getter != null && getter.IsVirtual) {
virtualAccessor = getter;
} else if (setter != null && setter.IsVirtual) {
virtualAccessor = setter;
} else {
virtualAccessor = null;
}
if (virtualAccessor != null) {
if (baseDefinitions.Add(RuntimeReflectionExtensions.GetRuntimeBaseDefinition(virtualAccessor))) {
return true;
}
} else if (member.DeclaringType == reflectedType) {
return true;
} else if (!member.IsPrivate() && (!member.IsStatic() || flattenHierarchy)) {
return true;
}
return false;
}
public static IEnumerable<EventInfo> GetInheritedEvents(this Type type, string name = null, bool flattenHierarchy = false) {
while (type.IsGenericParameter) {
type = type.GetBaseType();
}
var baseDefinitions = new HashSet<MethodInfo>(ReferenceEqualityComparer<MethodInfo>.Instance);
foreach (var ancestor in type.Ancestors()) {
if (name != null) {
var declaredEvent = ancestor.GetDeclaredEvent(name);
if (declaredEvent != null && IncludeEvent(declaredEvent, type, baseDefinitions, flattenHierarchy)) {
yield return declaredEvent;
}
} else {
foreach (var declaredEvent in ancestor.GetDeclaredEvents()) {
if (IncludeEvent(declaredEvent, type, baseDefinitions, flattenHierarchy)) {
yield return declaredEvent;
}
}
}
}
}
private static bool IncludeEvent(EventInfo member, Type reflectedType, HashSet<MethodInfo> baseDefinitions, bool flattenHierarchy) {
var add = member.GetAddMethod(nonPublic: true);
var remove = member.GetRemoveMethod(nonPublic: true);
// TOOD: fire method?
MethodInfo virtualAccessor;
if (add != null && add.IsVirtual) {
virtualAccessor = add;
} else if (remove != null && remove.IsVirtual) {
virtualAccessor = remove;
} else {
virtualAccessor = null;
}
if (virtualAccessor != null) {
if (baseDefinitions.Add(RuntimeReflectionExtensions.GetRuntimeBaseDefinition(virtualAccessor))) {
return true;
}
} else if (member.DeclaringType == reflectedType) {
return true;
} else if (!member.IsPrivate() && (!member.IsStatic() || flattenHierarchy)) {
return true;
}
return false;
}
public static IEnumerable<FieldInfo> GetInheritedFields(this Type type, string name = null, bool flattenHierarchy = false) {
while (type.IsGenericParameter) {
type = type.GetBaseType();
}
foreach (var ancestor in type.Ancestors()) {
if (name != null) {
var declaredField = ancestor.GetDeclaredField(name);
if (declaredField != null && IncludeField(declaredField, type, flattenHierarchy)) {
yield return declaredField;
}
} else {
foreach (var declaredField in ancestor.GetDeclaredFields()) {
if (IncludeField(declaredField, type, flattenHierarchy)) {
yield return declaredField;
}
}
}
}
}
private static bool IncludeField(FieldInfo member, Type reflectedType, bool flattenHierarchy) {
if (member.DeclaringType == reflectedType) {
return true;
}
if (!member.IsPrivate && (!member.IsStatic || flattenHierarchy)) {
return true;
}
return false;
}
public static IEnumerable<MemberInfo> GetInheritedMembers(this Type type, string name = null, bool flattenHierarchy = false) {
var result =
type.GetInheritedMethods(name, flattenHierarchy).Cast<MethodInfo, MemberInfo>().Concat(
type.GetInheritedProperties(name, flattenHierarchy).Cast<PropertyInfo, MemberInfo>().Concat(
type.GetInheritedEvents(name, flattenHierarchy).Cast<EventInfo, MemberInfo>().Concat(
type.GetInheritedFields(name, flattenHierarchy).Cast<FieldInfo, MemberInfo>())));
if (name == null) {
return result.Concat<MemberInfo>(
type.GetDeclaredConstructors().Cast<ConstructorInfo, MemberInfo>().Concat(
type.GetDeclaredNestedTypes().Cast<TypeInfo, MemberInfo>()));
}
var nestedType = type.GetDeclaredNestedType(name);
return (nestedType != null) ? result.Concat(new[] { nestedType }) : result;
}
#endregion
#region Declared Members
public static IEnumerable<ConstructorInfo> GetDeclaredConstructors(this Type type) {
return type.GetConstructors(BindingFlags.DeclaredOnly | AllMembers);
}
public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type, string name = null) {
if (name == null) {
return type.GetMethods(BindingFlags.DeclaredOnly | AllMembers);
}
return type.GetMember(name, MemberTypes.Method, BindingFlags.DeclaredOnly | AllMembers).OfType<MethodInfo>();
}
public static IEnumerable<PropertyInfo> GetDeclaredProperties(this Type type) {
return type.GetProperties(BindingFlags.DeclaredOnly | AllMembers);
}
public static PropertyInfo GetDeclaredProperty(this Type type, string name) {
Debug.Assert(name != null);
return type.GetProperty(name, BindingFlags.DeclaredOnly | AllMembers);
}
public static IEnumerable<EventInfo> GetDeclaredEvents(this Type type) {
return type.GetEvents(BindingFlags.DeclaredOnly | AllMembers);
}
public static EventInfo GetDeclaredEvent(this Type type, string name) {
Debug.Assert(name != null);
return type.GetEvent(name, BindingFlags.DeclaredOnly | AllMembers);
}
public static IEnumerable<FieldInfo> GetDeclaredFields(this Type type) {
return type.GetFields(BindingFlags.DeclaredOnly | AllMembers);
}
public static FieldInfo GetDeclaredField(this Type type, string name) {
Debug.Assert(name != null);
return type.GetField(name, BindingFlags.DeclaredOnly | AllMembers);
}
public static IEnumerable<TypeInfo> GetDeclaredNestedTypes(this Type type) {
return type.GetNestedTypes(BindingFlags.DeclaredOnly | AllMembers);
}
public static TypeInfo GetDeclaredNestedType(this Type type, string name) {
Debug.Assert(name != null);
return type.GetNestedType(name, BindingFlags.DeclaredOnly | AllMembers);
}
public static IEnumerable<MemberInfo> GetDeclaredMembers(this Type type, string name = null) {
if (name == null) {
return type.GetMembers(BindingFlags.DeclaredOnly | AllMembers);
}
return type.GetMember(name, BindingFlags.DeclaredOnly | AllMembers);
}
#endregion
public static Type[] GetGenericTypeArguments(this Type type) {
return type.IsGenericType && !type.IsGenericTypeDefinition ? type.GetGenericArguments() : null;
}
public static Type[] GetGenericTypeParameters(this Type type) {
return type.IsGenericTypeDefinition ? type.GetGenericArguments() : null;
}
public static IEnumerable<Module> GetModules(this Assembly assembly) {
return assembly.GetModules();
}
public static IEnumerable<Type> GetImplementedInterfaces(this Type type) {
return type.GetInterfaces();
}
public static TypeCode GetTypeCode(this Type type) {
return Type.GetTypeCode(type);
}
public static MethodInfo GetMethod(this Delegate d) {
return d.GetMethodInfo();
}
public static bool IsDefined(this Assembly assembly, Type attributeType) {
return assembly.IsDefined(attributeType, false);
}
public static T GetCustomAttribute<T>(this Assembly assembly, bool inherit = false) where T : Attribute {
return (T)Attribute.GetCustomAttribute(assembly, typeof(T), inherit);
}
public static T GetCustomAttribute<T>(this MemberInfo member, bool inherit = false) where T : Attribute {
return (T)Attribute.GetCustomAttribute(member, typeof(T), inherit);
}
public static bool ContainsGenericParameters(this Type type) {
return type.ContainsGenericParameters;
}
public static bool IsInterface(this Type type) {
return type.IsInterface;
}
public static bool IsClass(this Type type) {
return type.IsClass;
}
public static bool IsGenericType(this Type type) {
return type.IsGenericType;
}
public static bool IsGenericTypeDefinition(this Type type) {
return type.IsGenericTypeDefinition;
}
public static bool IsSealed(this Type type) {
return type.IsSealed;
}
public static bool IsAbstract(this Type type) {
return type.IsAbstract;
}
public static bool IsPublic(this Type type) {
return type.IsPublic;
}
public static bool IsVisible(this Type type) {
return type.IsVisible;
}
public static Type GetBaseType(this Type type) {
return type.BaseType;
}
public static bool IsValueType(this Type type) {
return type.IsValueType;
}
public static bool IsEnum(this Type type) {
return type.IsEnum;
}
public static bool IsPrimitive(this Type type) {
return type.IsPrimitive;
}
public static GenericParameterAttributes GetGenericParameterAttributes(this Type type) {
return type.GenericParameterAttributes;
}
public static Type[] EmptyTypes = new Type[0];
public static object GetRawConstantValue(this FieldInfo field) {
if (!field.IsLiteral) {
throw new ArgumentException(field + " not a literal.");
}
object value = field.GetValue(null);
return field.FieldType.IsEnum() ? UnwrapEnumValue(value) : value;
}
/// <summary>
/// Converts a boxed enum value to the underlying integer value.
/// </summary>
public static object UnwrapEnumValue(object value) {
if (value == null) {
throw new ArgumentNullException(nameof(value));
}
switch (value.GetType().GetTypeCode()) {
case TypeCode.Byte:
return Convert.ToByte(value);
case TypeCode.Int16:
return Convert.ToInt16(value);
case TypeCode.Int32:
return Convert.ToInt32(value);
case TypeCode.Int64:
return Convert.ToInt64(value);
case TypeCode.SByte:
return Convert.ToSByte(value);
case TypeCode.UInt16:
return Convert.ToUInt16(value);
case TypeCode.UInt32:
return Convert.ToUInt32(value);
case TypeCode.UInt64:
return Convert.ToUInt64(value);
default:
throw new ArgumentException("Value must be a boxed enum.", nameof(value));
}
}
#if FEATURE_REFEMIT
#if FEATURE_ASSEMBLYBUILDER_DEFINEDYNAMICASSEMBLY
public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) {
return AssemblyBuilder.DefineDynamicAssembly(name, access);
}
#else
public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) {
return AppDomain.CurrentDomain.DefineDynamicAssembly(name, access);
}
#endif
#if !FEATURE_PDBEMIT
public static ModuleBuilder DefineDynamicModule(this AssemblyBuilder assembly, string name, bool emitDebugInfo) {
// ignore the flag
return assembly.DefineDynamicModule(name);
}
#endif
#endif
#region Signature and Type Formatting
// Generic type names have the arity (number of generic type paramters) appended at the end.
// For eg. the mangled name of System.List<T> is "List`1". This mangling is done to enable multiple
// generic types to exist as long as they have different arities.
public const char GenericArityDelimiter = '`';
public static StringBuilder FormatSignature(StringBuilder result, MethodBase method) {
return FormatSignature(result, method, t => t.FullName);
}
public static StringBuilder FormatSignature(StringBuilder result, MethodBase method, Func<Type, string> nameDispenser) {
ContractUtils.RequiresNotNull(result, nameof(result));
ContractUtils.RequiresNotNull(method, nameof(method));
ContractUtils.RequiresNotNull(nameDispenser, nameof(nameDispenser));
MethodInfo methodInfo = method as MethodInfo;
if (methodInfo != null) {
FormatTypeName(result, methodInfo.ReturnType, nameDispenser);
result.Append(' ');
}
#if FEATURE_REFEMIT && !NETCOREAPP2_0 && !NETCOREAPP2_1 && !NETSTANDARD2_0
MethodBuilder builder = method as MethodBuilder;
if (builder != null) {
result.Append(builder.Signature);
return result;
}
ConstructorBuilder cb = method as ConstructorBuilder;
if (cb != null) {
result.Append(cb.Signature);
return result;
}
#endif
FormatTypeName(result, method.DeclaringType, nameDispenser);
result.Append("::");
result.Append(method.Name);
if (!method.IsConstructor) {
FormatTypeArgs(result, method.GetGenericArguments(), nameDispenser);
}
result.Append("(");
if (!method.ContainsGenericParameters) {
ParameterInfo[] ps = method.GetParameters();
for (int i = 0; i < ps.Length; i++) {
if (i > 0) result.Append(", ");
FormatTypeName(result, ps[i].ParameterType, nameDispenser);
if (!System.String.IsNullOrEmpty(ps[i].Name)) {
result.Append(" ");
result.Append(ps[i].Name);
}
}
} else {
result.Append("?");
}
result.Append(")");
return result;
}
public static StringBuilder FormatTypeName(StringBuilder result, Type type) {
return FormatTypeName(result, type, t => t.FullName);
}
public static StringBuilder FormatTypeName(StringBuilder result, Type type, Func<Type, string> nameDispenser) {
ContractUtils.RequiresNotNull(result, nameof(result));
ContractUtils.RequiresNotNull(type, nameof(type));
ContractUtils.RequiresNotNull(nameDispenser, nameof(nameDispenser));
if (type.IsGenericType()) {
Type genType = type.GetGenericTypeDefinition();
string genericName = nameDispenser(genType).Replace('+', '.');
int tickIndex = genericName.IndexOf('`');
result.Append(tickIndex != -1 ? genericName.Substring(0, tickIndex) : genericName);
Type[] typeArgs = type.GetGenericArguments();
if (type.IsGenericTypeDefinition()) {
result.Append('<');
result.Append(',', typeArgs.Length - 1);
result.Append('>');
} else {
FormatTypeArgs(result, typeArgs, nameDispenser);
}
} else if (type.IsGenericParameter) {
result.Append(type.Name);
} else {
// cut namespace off:
result.Append(nameDispenser(type).Replace('+', '.'));
}
return result;
}
public static StringBuilder FormatTypeArgs(StringBuilder result, Type[] types) {
return FormatTypeArgs(result, types, (t) => t.FullName);
}
public static StringBuilder FormatTypeArgs(StringBuilder result, Type[] types, Func<Type, string> nameDispenser) {
ContractUtils.RequiresNotNull(result, nameof(result));
ContractUtils.RequiresNotNullItems(types, nameof(types));
ContractUtils.RequiresNotNull(nameDispenser, nameof(nameDispenser));
if (types.Length > 0) {
result.Append("<");
for (int i = 0; i < types.Length; i++) {
if (i > 0) result.Append(", ");
FormatTypeName(result, types[i], nameDispenser);
}
result.Append(">");
}
return result;
}
internal static string ToValidTypeName(string str) {
if (String.IsNullOrEmpty(str)) {
return "_";
}
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < str.Length; i++) {
if (str[i] == '\0' || str[i] == '.' || str[i] == '*' || str[i] == '+' || str[i] == '[' || str[i] == ']' || str[i] == '\\') {
sb[i] = '_';
}
}
return sb.ToString();
}
public static string GetNormalizedTypeName(Type type) {
string name = type.Name;
if (type.IsGenericType()) {
return GetNormalizedTypeName(name);
}
return name;
}
public static string GetNormalizedTypeName(string typeName) {
Debug.Assert(typeName.IndexOf('.') == -1); // This is the simple name, not the full name
int backtick = typeName.IndexOf(GenericArityDelimiter);
if (backtick != -1) return typeName.Substring(0, backtick);
return typeName;
}
#endregion
#region Delegates and Dynamic Methods
/// <summary>
/// Creates an open delegate for the given (dynamic)method.
/// </summary>
public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType) {
return CreateDelegate(methodInfo, delegateType, null);
}
/// <summary>
/// Creates a closed delegate for the given (dynamic)method.
/// </summary>
public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType, object target) {
#if FEATURE_LCG
if (methodInfo is DynamicMethod dm) {
return dm.CreateDelegate(delegateType, target);
}
#endif
return Delegate.CreateDelegate(delegateType, target, methodInfo);
}
#if FEATURE_LCG
public static bool IsDynamicMethod(MethodBase method) => IsDynamicMethodInternal(method);
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool IsDynamicMethodInternal(MethodBase method) {
return method is DynamicMethod;
}
#else
public static bool IsDynamicMethod(MethodBase method) {
return false;
}
#endif
public static void GetDelegateSignature(Type delegateType, out ParameterInfo[] parameterInfos, out ParameterInfo returnInfo) {
ContractUtils.RequiresNotNull(delegateType, nameof(delegateType));
MethodInfo invokeMethod = delegateType.GetMethod("Invoke");
ContractUtils.Requires(invokeMethod != null, nameof(delegateType), Strings.InvalidDelegate);
parameterInfos = invokeMethod.GetParameters();
returnInfo = invokeMethod.ReturnParameter;
}
/// <summary>
/// Gets a Func of CallSite, object * paramCnt, object delegate type
/// that's suitable for use in a non-strongly typed call site.
/// </summary>
public static Type GetObjectCallSiteDelegateType(int paramCnt) {
switch (paramCnt) {
case 0: return typeof(Func<CallSite, object, object>);
case 1: return typeof(Func<CallSite, object, object, object>);
case 2: return typeof(Func<CallSite, object, object, object, object>);
case 3: return typeof(Func<CallSite, object, object, object, object, object>);
case 4: return typeof(Func<CallSite, object, object, object, object, object, object>);
case 5: return typeof(Func<CallSite, object, object, object, object, object, object, object>);
case 6: return typeof(Func<CallSite, object, object, object, object, object, object, object, object>);
case 7: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object>);
case 8: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object>);
case 9: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object>);
case 10: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object>);
case 11: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object>);
case 12: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object>);
case 13: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>);
case 14: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>);
default:
#if FEATURE_REFEMIT
Type[] paramTypes = new Type[paramCnt + 2];
paramTypes[0] = typeof(CallSite);
paramTypes[1] = typeof(object);
for (int i = 0; i < paramCnt; i++) {
paramTypes[i + 2] = typeof(object);
}
return Snippets.Shared.DefineDelegate("InvokeDelegate" + paramCnt, typeof(object), paramTypes);
#else
throw new NotSupportedException("Signature not supported on this platform.");
#endif
}
}
#if FEATURE_LCG
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework")]
internal static DynamicMethod RawCreateDynamicMethod(string name, Type returnType, Type[] parameterTypes) {
//
// WARNING: we set restrictedSkipVisibility == true (last parameter)
// setting this bit will allow accessing nonpublic members
// for more information see http://msdn.microsoft.com/en-us/library/bb348332.aspx
//
return new DynamicMethod(name, returnType, parameterTypes, true);
}
#endif
#endregion
#region Methods and Parameters
public static MethodBase[] GetMethodInfos(MemberInfo[] members) {
return ArrayUtils.ConvertAll<MemberInfo, MethodBase>(
members,
delegate (MemberInfo inp) { return (MethodBase)inp; });
}
public static Type[] GetParameterTypes(ParameterInfo[] parameterInfos) {
return GetParameterTypes((IList<ParameterInfo>)parameterInfos);
}
public static Type[] GetParameterTypes(IList<ParameterInfo> parameterInfos) {
Type[] result = new Type[parameterInfos.Count];
for (int i = 0; i < result.Length; i++) {
result[i] = parameterInfos[i].ParameterType;
}
return result;
}
public static Type GetReturnType(this MethodBase mi) {
return (mi.IsConstructor) ? mi.DeclaringType : ((MethodInfo)mi).ReturnType;
}
public static bool SignatureEquals(MethodInfo method, params Type[] requiredSignature) {
ContractUtils.RequiresNotNull(method, nameof(method));
Type[] actualTypes = GetParameterTypes(method.GetParameters());
Debug.Assert(actualTypes.Length == requiredSignature.Length - 1);
int i = 0;
while (i < actualTypes.Length) {
if (actualTypes[i] != requiredSignature[i]) return false;
i++;
}
return method.ReturnType == requiredSignature[i];
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static bool IsExtension(this MemberInfo member) {
var dlrExtension = typeof(ExtensionAttribute);
if (member.IsDefined(dlrExtension, false)) {
return true;
}
return false;
}
public static bool IsOutParameter(this ParameterInfo pi) {
// not using IsIn/IsOut properties as they are not available in Silverlight:
return pi.ParameterType.IsByRef && (pi.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out;
}
/// <summary>
/// Returns <c>true</c> if the specified parameter is mandatory, i.e. is not optional and doesn't have a default value.
/// </summary>
public static bool IsMandatory(this ParameterInfo pi) {
return (pi.Attributes & ParameterAttributes.Optional) == 0 && !pi.HasDefaultValue();
}
public static bool HasDefaultValue(this ParameterInfo pi) {
return (pi.Attributes & ParameterAttributes.HasDefault) != 0;
}
public static bool ProhibitsNull(this ParameterInfo parameter) {
return parameter.IsDefined(typeof(NotNullAttribute), false);
}
public static bool ProhibitsNullItems(this ParameterInfo parameter) {
return parameter.IsDefined(typeof(NotNullItemsAttribute), false);
}
public static bool IsParamArray(this ParameterInfo parameter) {
return parameter.IsDefined(typeof(ParamArrayAttribute), false);
}
public static bool IsParamDictionary(this ParameterInfo parameter) {
return parameter.IsDefined(typeof(ParamDictionaryAttribute), false);
}
public static bool IsParamsMethod(MethodBase method) {
return IsParamsMethod(method.GetParameters());
}
public static bool IsParamsMethod(ParameterInfo[] pis) {
foreach (ParameterInfo pi in pis) {
if (pi.IsParamArray() || pi.IsParamDictionary()) return true;
}
return false;
}