forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlatformExtensions.cs
More file actions
985 lines (797 loc) · 40.5 KB
/
Copy pathPlatformExtensions.cs
File metadata and controls
985 lines (797 loc) · 40.5 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
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
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Xml;
using ServiceStack.Text;
namespace ServiceStack
{
public static class PlatformExtensions
{
[Obsolete("Use type.IsInterface")]
public static bool IsInterface(this Type type) => type.IsInterface;
[Obsolete("Use type.IsArray")]
public static bool IsArray(this Type type) => type.IsArray;
[Obsolete("Use type.IsValueType")]
public static bool IsValueType(this Type type) => type.IsValueType;
[Obsolete("Use type.IsGenericType")]
public static bool IsGeneric(this Type type) => type.IsGenericType;
[Obsolete("Use type.BaseType")]
public static Type BaseType(this Type type) => type.BaseType;
[Obsolete("Use pi.ReflectedType")]
public static Type ReflectedType(this PropertyInfo pi) => pi.ReflectedType;
[Obsolete("Use fi.ReflectedType")]
public static Type ReflectedType(this FieldInfo fi) => fi.ReflectedType;
[Obsolete("Use type.GetGenericTypeDefinition()")]
public static Type GenericTypeDefinition(this Type type) => type.GetGenericTypeDefinition();
[Obsolete("Use type.GetInterfaces()")]
public static Type[] GetTypeInterfaces(this Type type) => type.GetInterfaces();
[Obsolete("Use type.GetGenericArguments()")]
public static Type[] GetTypeGenericArguments(this Type type) => type.GetGenericArguments();
[Obsolete("Use type.GetConstructor(Type.EmptyTypes)")]
public static ConstructorInfo GetEmptyConstructor(this Type type) => type.GetConstructor(Type.EmptyTypes);
[Obsolete("Use type.GetConstructors()")]
public static IEnumerable<ConstructorInfo> GetAllConstructors(this Type type) => type.GetConstructors();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static PropertyInfo[] GetTypesPublicProperties(this Type subType)
{
return subType.GetProperties(
BindingFlags.FlattenHierarchy |
BindingFlags.Public |
BindingFlags.Instance);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static PropertyInfo[] GetTypesProperties(this Type subType)
{
return subType.GetProperties(
BindingFlags.FlattenHierarchy |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);
}
[Obsolete("Use type.Assembly")]
public static Assembly GetAssembly(this Type type) => type.Assembly;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static FieldInfo[] Fields(this Type type)
{
return type.GetFields(
BindingFlags.FlattenHierarchy |
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PropertyInfo[] Properties(this Type type)
{
return type.GetProperties(
BindingFlags.FlattenHierarchy |
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static FieldInfo[] GetAllFields(this Type type) => type.IsInterface ? TypeConstants.EmptyFieldInfoArray : type.Fields();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static FieldInfo[] GetPublicFields(this Type type) => type.IsInterface
? TypeConstants.EmptyFieldInfoArray
: type.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance).ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MemberInfo[] GetPublicMembers(this Type type) => type.GetMembers(BindingFlags.Public | BindingFlags.Instance);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MemberInfo[] GetAllPublicMembers(this Type type) =>
type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MethodInfo GetStaticMethod(this Type type, string methodName) =>
type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MethodInfo GetInstanceMethod(this Type type, string methodName) =>
type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
[Obsolete("Use fn.Method")]
public static MethodInfo Method(this Delegate fn) => fn.Method;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasAttribute<T>(this Type type) => type.AllAttributes().Any(x => x.GetType() == typeof(T));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasAttribute<T>(this PropertyInfo pi) => pi.AllAttributes().Any(x => x.GetType() == typeof(T));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasAttribute<T>(this FieldInfo fi) => fi.AllAttributes().Any(x => x.GetType() == typeof(T));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasAttribute<T>(this MethodInfo mi) => mi.AllAttributes().Any(x => x.GetType() == typeof(T));
private static Dictionary<MemberInfo, bool> hasAttributeCache = new Dictionary<MemberInfo, bool>();
public static bool HasAttributeCached<T>(this MemberInfo memberInfo)
{
if (hasAttributeCache.TryGetValue(memberInfo, out var hasAttr))
return hasAttr;
hasAttr = memberInfo is Type t
? t.AllAttributes().Any(x => x.GetType() == typeof(T))
: memberInfo is PropertyInfo pi
? pi.AllAttributes().Any(x => x.GetType() == typeof(T))
: memberInfo is FieldInfo fi
? fi.AllAttributes().Any(x => x.GetType() == typeof(T))
: memberInfo is MethodInfo mi
? mi.AllAttributes().Any(x => x.GetType() == typeof(T))
: throw new NotSupportedException(memberInfo.GetType().Name);
Dictionary<MemberInfo, bool> snapshot, newCache;
do
{
snapshot = hasAttributeCache;
newCache = new Dictionary<MemberInfo, bool>(hasAttributeCache) {
[memberInfo] = hasAttr
};
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref hasAttributeCache, newCache, snapshot), snapshot));
return hasAttr;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasAttributeNamed(this Type type, string name)
{
var normalizedAttr = name.Replace("Attribute", "").ToLower();
return type.AllAttributes().Any(x => x.GetType().Name.Replace("Attribute", "").ToLower() == normalizedAttr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasAttributeNamed(this PropertyInfo pi, string name)
{
var normalizedAttr = name.Replace("Attribute", "").ToLower();
return pi.AllAttributes().Any(x => x.GetType().Name.Replace("Attribute", "").ToLower() == normalizedAttr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasAttributeNamed(this FieldInfo fi, string name)
{
var normalizedAttr = name.Replace("Attribute", "").ToLower();
return fi.AllAttributes().Any(x => x.GetType().Name.Replace("Attribute", "").ToLower() == normalizedAttr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasAttributeNamed(this MemberInfo mi, string name)
{
var normalizedAttr = name.Replace("Attribute", "").ToLower();
return mi.AllAttributes().Any(x => x.GetType().Name.Replace("Attribute", "").ToLower() == normalizedAttr);
}
const string DataContract = "DataContractAttribute";
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsDto(this Type type)
{
if (type == null)
return false;
return !Env.IsMono
? type.HasAttribute<DataContractAttribute>()
: type.GetCustomAttributes(true).Any(x => x.GetType().Name == DataContract);
}
[Obsolete("Use pi.GetGetMethod(nonPublic)")]
public static MethodInfo PropertyGetMethod(this PropertyInfo pi, bool nonPublic = false) => pi.GetGetMethod(nonPublic);
[Obsolete("Use type.GetInterfaces()")]
public static Type[] Interfaces(this Type type) => type.GetInterfaces();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PropertyInfo[] AllProperties(this Type type) =>
type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
//Should only register Runtime Attributes on StartUp, So using non-ThreadSafe Dictionary is OK
static Dictionary<string, List<Attribute>> propertyAttributesMap
= new Dictionary<string, List<Attribute>>();
static Dictionary<Type, List<Attribute>> typeAttributesMap
= new Dictionary<Type, List<Attribute>>();
public static void ClearRuntimeAttributes()
{
propertyAttributesMap = new Dictionary<string, List<Attribute>>();
typeAttributesMap = new Dictionary<Type, List<Attribute>>();
}
internal static string UniqueKey(this PropertyInfo pi)
{
if (pi.DeclaringType == null)
throw new ArgumentException("Property '{0}' has no DeclaringType".Fmt(pi.Name));
return pi.DeclaringType.Namespace + "." + pi.DeclaringType.Name + "." + pi.Name;
}
public static Type AddAttributes(this Type type, params Attribute[] attrs)
{
if (!typeAttributesMap.TryGetValue(type, out var typeAttrs))
typeAttributesMap[type] = typeAttrs = new List<Attribute>();
typeAttrs.AddRange(attrs);
return type;
}
/// <summary>
/// Add a Property attribute at runtime.
/// <para>Not threadsafe, should only add attributes on Startup.</para>
/// </summary>
public static PropertyInfo AddAttributes(this PropertyInfo propertyInfo, params Attribute[] attrs)
{
var key = propertyInfo.UniqueKey();
if (!propertyAttributesMap.TryGetValue(key, out var propertyAttrs))
propertyAttributesMap[key] = propertyAttrs = new List<Attribute>();
propertyAttrs.AddRange(attrs);
return propertyInfo;
}
/// <summary>
/// Add a Property attribute at runtime.
/// <para>Not threadsafe, should only add attributes on Startup.</para>
/// </summary>
public static PropertyInfo ReplaceAttribute(this PropertyInfo propertyInfo, Attribute attr)
{
var key = propertyInfo.UniqueKey();
if (!propertyAttributesMap.TryGetValue(key, out var propertyAttrs))
propertyAttributesMap[key] = propertyAttrs = new List<Attribute>();
propertyAttrs.RemoveAll(x => x.GetType() == attr.GetType());
propertyAttrs.Add(attr);
return propertyInfo;
}
public static List<TAttr> GetAttributes<TAttr>(this PropertyInfo propertyInfo)
{
return !propertyAttributesMap.TryGetValue(propertyInfo.UniqueKey(), out var propertyAttrs)
? new List<TAttr>()
: propertyAttrs.OfType<TAttr>().ToList();
}
public static List<Attribute> GetAttributes(this PropertyInfo propertyInfo)
{
return !propertyAttributesMap.TryGetValue(propertyInfo.UniqueKey(), out var propertyAttrs)
? new List<Attribute>()
: propertyAttrs.ToList();
}
public static List<Attribute> GetAttributes(this PropertyInfo propertyInfo, Type attrType)
{
return !propertyAttributesMap.TryGetValue(propertyInfo.UniqueKey(), out var propertyAttrs)
? new List<Attribute>()
: propertyAttrs.Where(x => attrType.IsInstanceOf(x.GetType())).ToList();
}
public static object[] AllAttributes(this PropertyInfo propertyInfo)
{
var attrs = propertyInfo.GetCustomAttributes(true);
var runtimeAttrs = propertyInfo.GetAttributes();
if (runtimeAttrs.Count == 0)
return attrs;
runtimeAttrs.AddRange(attrs.Cast<Attribute>());
return runtimeAttrs.Cast<object>().ToArray();
}
public static object[] AllAttributes(this PropertyInfo propertyInfo, Type attrType)
{
var attrs = propertyInfo.GetCustomAttributes(attrType, true);
var runtimeAttrs = propertyInfo.GetAttributes(attrType);
if (runtimeAttrs.Count == 0)
return attrs;
runtimeAttrs.AddRange(attrs.Cast<Attribute>());
return runtimeAttrs.Cast<object>().ToArray();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object[] AllAttributes(this ParameterInfo paramInfo) => paramInfo.GetCustomAttributes(true);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object[] AllAttributes(this FieldInfo fieldInfo) => fieldInfo.GetCustomAttributes(true);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object[] AllAttributes(this MemberInfo memberInfo) => memberInfo.GetCustomAttributes(true);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object[] AllAttributes(this ParameterInfo paramInfo, Type attrType) => paramInfo.GetCustomAttributes(attrType, true);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object[] AllAttributes(this MemberInfo memberInfo, Type attrType)
{
var prop = memberInfo as PropertyInfo;
return prop != null
? prop.AllAttributes(attrType)
: memberInfo.GetCustomAttributes(attrType, true);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object[] AllAttributes(this FieldInfo fieldInfo, Type attrType) => fieldInfo.GetCustomAttributes(attrType, true);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object[] AllAttributes(this Type type) => type.GetCustomAttributes(true).Union(type.GetRuntimeAttributes()).ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object[] AllAttributes(this Type type, Type attrType) =>
type.GetCustomAttributes(attrType, true).Union(type.GetRuntimeAttributes(attrType)).ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object[] AllAttributes(this Assembly assembly) => assembly.GetCustomAttributes(true).ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TAttr[] AllAttributes<TAttr>(this ParameterInfo pi) => pi.AllAttributes(typeof(TAttr)).Cast<TAttr>().ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TAttr[] AllAttributes<TAttr>(this MemberInfo mi) => mi.AllAttributes(typeof(TAttr)).Cast<TAttr>().ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TAttr[] AllAttributes<TAttr>(this FieldInfo fi) => fi.AllAttributes(typeof(TAttr)).Cast<TAttr>().ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TAttr[] AllAttributes<TAttr>(this PropertyInfo pi) => pi.AllAttributes(typeof(TAttr)).Cast<TAttr>().ToArray();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static IEnumerable<T> GetRuntimeAttributes<T>(this Type type) => typeAttributesMap.TryGetValue(type, out var attrs)
? attrs.OfType<T>()
: new List<T>();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static IEnumerable<Attribute> GetRuntimeAttributes(this Type type, Type attrType = null) => typeAttributesMap.TryGetValue(type, out var attrs)
? attrs.Where(x => attrType == null || attrType.IsInstanceOf(x.GetType()))
: new List<Attribute>();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TAttr[] AllAttributes<TAttr>(this Type type)
{
return type.GetCustomAttributes(typeof(TAttr), true)
.OfType<TAttr>()
.Union(type.GetRuntimeAttributes<TAttr>())
.ToArray();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TAttr FirstAttribute<TAttr>(this Type type) where TAttr : class
{
return (TAttr)type.GetCustomAttributes(typeof(TAttr), true)
.FirstOrDefault()
?? type.GetRuntimeAttributes<TAttr>().FirstOrDefault();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TAttribute FirstAttribute<TAttribute>(this MemberInfo memberInfo)
{
return memberInfo.AllAttributes<TAttribute>().FirstOrDefault();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TAttribute FirstAttribute<TAttribute>(this ParameterInfo paramInfo)
{
return paramInfo.AllAttributes<TAttribute>().FirstOrDefault();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo)
{
return propertyInfo.AllAttributes<TAttribute>().FirstOrDefault();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Type FirstGenericTypeDefinition(this Type type)
{
var genericType = type.FirstGenericType();
return genericType != null ? genericType.GetGenericTypeDefinition() : null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsDynamic(this Assembly assembly) => ReflectionOptimizer.Instance.IsDynamic(assembly);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MethodInfo GetStaticMethod(this Type type, string methodName, Type[] types)
{
return types == null
? type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static)
: type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static, null, types, null);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MethodInfo GetMethodInfo(this Type type, string methodName, Type[] types = null) => types == null
? type.GetMethod(methodName)
: type.GetMethod(methodName, types);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object InvokeMethod(this Delegate fn, object instance, object[] parameters = null) =>
fn.Method.Invoke(instance, parameters ?? new object[] { });
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static FieldInfo GetPublicStaticField(this Type type, string fieldName) =>
type.GetField(fieldName, BindingFlags.Public | BindingFlags.Static);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Delegate MakeDelegate(this MethodInfo mi, Type delegateType, bool throwOnBindFailure = true) =>
Delegate.CreateDelegate(delegateType, mi, throwOnBindFailure);
[Obsolete("Use type.GetGenericArguments()")]
public static Type[] GenericTypeArguments(this Type type) => type.GetGenericArguments();
[Obsolete("Use type.GetConstructors()")]
public static ConstructorInfo[] DeclaredConstructors(this Type type) => type.GetConstructors();
[Obsolete("Use type.IsAssignableFrom(fromType)")]
public static bool AssignableFrom(this Type type, Type fromType) => type.IsAssignableFrom(fromType);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsStandardClass(this Type type) => type.IsClass && !type.IsAbstract && !type.IsInterface;
[Obsolete("Use type.IsAbstract")]
public static bool IsAbstract(this Type type) => type.IsAbstract;
[Obsolete("Use type.GetProperty(propertyName)")]
public static PropertyInfo GetPropertyInfo(this Type type, string propertyName) => type.GetProperty(propertyName);
[Obsolete("Use type.GetField(fieldName)")]
public static FieldInfo GetFieldInfo(this Type type, string fieldName) => type.GetField(fieldName);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static FieldInfo[] GetWritableFields(this Type type) =>
type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
[Obsolete("Use pi.GetSetMethod(nonPublic)")]
public static MethodInfo SetMethod(this PropertyInfo pi, bool nonPublic = true) =>
pi.GetSetMethod(nonPublic);
[Obsolete("Use pi.GetGetMethod(nonPublic)")]
public static MethodInfo GetMethodInfo(this PropertyInfo pi, bool nonPublic = true) =>
pi.GetGetMethod(nonPublic);
[Obsolete("Use type.IsInstanceOfType(instance)")]
public static bool InstanceOfType(this Type type, object instance) => type.IsInstanceOfType(instance);
[Obsolete("Use type.IsAssignableFrom(fromType)")]
public static bool IsAssignableFromType(this Type type, Type fromType) => type.IsAssignableFrom(fromType);
[Obsolete("Use type.IsClass")]
public static bool IsClass(this Type type) => type.IsClass;
[Obsolete("Use type.IsEnum")]
public static bool IsEnum(this Type type) => type.IsEnum;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsEnumFlags(this Type type) => type.IsEnum && type.FirstAttribute<FlagsAttribute>() != null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsUnderlyingEnum(this Type type) => type.IsEnum || type.UnderlyingSystemType.IsEnum;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MethodInfo[] GetInstanceMethods(this Type type) =>
type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
[Obsolete("Use type.GetMethods()")]
public static MethodInfo[] GetMethodInfos(this Type type) => type.GetMethods();
[Obsolete("Use type.GetProperties()")]
public static PropertyInfo[] GetPropertyInfos(this Type type) => type.GetProperties();
[Obsolete("Use type.IsGenericTypeDefinition")]
public static bool IsGenericTypeDefinition(this Type type) => type.IsGenericTypeDefinition;
[Obsolete("Use type.IsGenericType")]
public static bool IsGenericType(this Type type) => type.IsGenericType;
[Obsolete("Use type.ContainsGenericParameters")]
public static bool ContainsGenericParameters(this Type type) => type.ContainsGenericParameters;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string GetDeclaringTypeName(this Type type)
{
if (type.DeclaringType != null)
return type.DeclaringType.Name;
if (type.ReflectedType != null)
return type.ReflectedType.Name;
return null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string GetDeclaringTypeName(this MemberInfo mi)
{
if (mi.DeclaringType != null)
return mi.DeclaringType.Name;
return mi.ReflectedType.Name;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType)
{
return Delegate.CreateDelegate(delegateType, methodInfo);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType, object target)
{
return Delegate.CreateDelegate(delegateType, target, methodInfo);
}
[Obsolete("Use type.GetElementType()")]
public static Type ElementType(this Type type) => type.GetElementType();
public static Type GetCollectionType(this Type type)
{
return type.GetElementType()
?? type.GetGenericArguments().LastOrDefault() //new[] { str }.Select(x => new Type()) => WhereSelectArrayIterator<string,Type>
?? (type.BaseType != null && type.BaseType != typeof(object) ? type.BaseType.GetCollectionType() : null); //e.g. ArrayOfString : List<string>
}
static Dictionary<string, Type> GenericTypeCache = new Dictionary<string, Type>();
public static Type GetCachedGenericType(this Type type, params Type[] argTypes)
{
if (!type.IsGenericTypeDefinition)
throw new ArgumentException(type.FullName + " is not a Generic Type Definition");
if (argTypes == null)
argTypes = TypeConstants.EmptyTypeArray;
var sb = StringBuilderThreadStatic.Allocate()
.Append(type.FullName);
foreach (var argType in argTypes)
{
sb.Append('|')
.Append(argType.FullName);
}
var key = StringBuilderThreadStatic.ReturnAndFree(sb);
if (GenericTypeCache.TryGetValue(key, out var genericType))
return genericType;
genericType = type.MakeGenericType(argTypes);
Dictionary<string, Type> snapshot, newCache;
do
{
snapshot = GenericTypeCache;
newCache = new Dictionary<string, Type>(GenericTypeCache) {
[key] = genericType
};
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref GenericTypeCache, newCache, snapshot), snapshot));
return genericType;
}
private static readonly ConcurrentDictionary<Type, ObjectDictionaryDefinition> toObjectMapCache =
new ConcurrentDictionary<Type, ObjectDictionaryDefinition>();
internal class ObjectDictionaryDefinition
{
public Type Type;
public readonly List<ObjectDictionaryFieldDefinition> Fields = new List<ObjectDictionaryFieldDefinition>();
public readonly Dictionary<string, ObjectDictionaryFieldDefinition> FieldsMap = new Dictionary<string, ObjectDictionaryFieldDefinition>();
public void Add(string name, ObjectDictionaryFieldDefinition fieldDef)
{
Fields.Add(fieldDef);
FieldsMap[name] = fieldDef;
}
}
internal class ObjectDictionaryFieldDefinition
{
public string Name;
public Type Type;
public GetMemberDelegate GetValueFn;
public SetMemberDelegate SetValueFn;
public Type ConvertType;
public GetMemberDelegate ConvertValueFn;
public void SetValue(object instance, object value)
{
if (SetValueFn == null)
return;
if (Type != typeof(object))
{
if (value is IEnumerable<KeyValuePair<string, object>> dictionary)
{
value = dictionary.FromObjectDictionary(Type);
}
if (!Type.IsInstanceOfType(value))
{
lock (this)
{
//Only caches object converter used on first use
if (ConvertType == null)
{
ConvertType = value.GetType();
ConvertValueFn = TypeConverter.CreateTypeConverter(ConvertType, Type);
}
}
if (ConvertType.IsInstanceOfType(value))
{
value = ConvertValueFn(value);
}
else
{
var tempConvertFn = TypeConverter.CreateTypeConverter(value.GetType(), Type);
value = tempConvertFn(value);
}
}
}
SetValueFn(instance, value);
}
}
public static Dictionary<string, object> ToObjectDictionary(this object obj)
{
if (obj == null)
return null;
if (obj is Dictionary<string, object> alreadyDict)
return alreadyDict;
if (obj is IDictionary<string, object> interfaceDict)
return new Dictionary<string, object>(interfaceDict);
var to = new Dictionary<string, object>();
if (obj is Dictionary<string, string> stringDict)
{
foreach (var entry in stringDict)
{
to[entry.Key] = entry.Value;
}
return to;
}
if (obj is IDictionary d)
{
foreach (var key in d.Keys)
{
to[key.ToString()] = d[key];
}
return to;
}
if (obj is NameValueCollection nvc)
{
for (var i = 0; i < nvc.Count; i++)
{
to[nvc.GetKey(i)] = nvc.Get(i);
}
return to;
}
if (obj is IEnumerable<KeyValuePair<string, object>> objKvps)
{
foreach (var kvp in objKvps)
{
to[kvp.Key] = kvp.Value;
}
return to;
}
if (obj is IEnumerable<KeyValuePair<string, string>> strKvps)
{
foreach (var kvp in strKvps)
{
to[kvp.Key] = kvp.Value;
}
return to;
}
var type = obj.GetType();
if (type.GetKeyValuePairsTypes(out var keyType, out var valueType, out var kvpType) && obj is IEnumerable e)
{
var keyGetter = TypeProperties.Get(kvpType).GetPublicGetter("Key");
var valueGetter = TypeProperties.Get(kvpType).GetPublicGetter("Value");
foreach (var entry in e)
{
var key = keyGetter(entry);
var value = valueGetter(entry);
to[key.ConvertTo<string>()] = value;
}
return to;
}
if (obj is KeyValuePair<string, object> objKvp)
return new Dictionary<string, object> { { nameof(objKvp.Key), objKvp.Key }, { nameof(objKvp.Value), objKvp.Value } };
if (obj is KeyValuePair<string, string> strKvp)
return new Dictionary<string, object> { { nameof(strKvp.Key), strKvp.Key }, { nameof(strKvp.Value), strKvp.Value } };
if (type.GetKeyValuePairTypes(out _, out var _))
{
return new Dictionary<string, object> {
{ "Key", TypeProperties.Get(type).GetPublicGetter("Key")(obj).ConvertTo<string>() },
{ "Value", TypeProperties.Get(type).GetPublicGetter("Value")(obj) },
};
}
if (!toObjectMapCache.TryGetValue(type, out var def))
toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type);
foreach (var fieldDef in def.Fields)
{
to[fieldDef.Name] = fieldDef.GetValueFn(obj);
}
return to;
}
public static Type GetKeyValuePairsTypeDef(this Type dictType)
{
//matches IDictionary<,>, IReadOnlyDictionary<,>, List<KeyValuePair<string, object>>
var genericDef = dictType.GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>));
if (genericDef == null)
return null;
var genericEnumType = genericDef.GetGenericArguments()[0];
return GetKeyValuePairTypeDef(genericEnumType);
}
public static Type GetKeyValuePairTypeDef(this Type genericEnumType) => genericEnumType.GetTypeWithGenericTypeDefinitionOf(typeof(KeyValuePair<,>));
public static bool GetKeyValuePairsTypes(this Type dictType, out Type keyType, out Type valueType) =>
dictType.GetKeyValuePairsTypes(out keyType, out valueType, out _);
public static bool GetKeyValuePairsTypes(this Type dictType, out Type keyType, out Type valueType, out Type kvpType)
{
//matches IDictionary<,>, IReadOnlyDictionary<,>, List<KeyValuePair<string, object>>
var genericDef = dictType.GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>));
if (genericDef != null)
{
kvpType = genericDef.GetGenericArguments()[0];
if (GetKeyValuePairTypes(kvpType, out keyType, out valueType))
return true;
}
kvpType = keyType = valueType = null;
return false;
}
public static bool GetKeyValuePairTypes(this Type kvpType, out Type keyType, out Type valueType)
{
var genericKvps = kvpType.GetTypeWithGenericTypeDefinitionOf(typeof(KeyValuePair<,>));
if (genericKvps != null)
{
var genericArgs = kvpType.GetGenericArguments();
keyType = genericArgs[0];
valueType = genericArgs[1];
return true;
}
keyType = valueType = null;
return false;
}
public static object FromObjectDictionary(this IEnumerable<KeyValuePair<string, object>> values, Type type)
{
if (values == null)
return null;
var alreadyDict = typeof(IEnumerable<KeyValuePair<string, object>>).IsAssignableFrom(type);
if (alreadyDict)
return values;
var to = type.CreateInstance();
if (to is IDictionary d)
{
if (type.GetKeyValuePairsTypes(out var toKeyType, out var toValueType))
{
foreach (var entry in values)
{
var toKey = entry.Key.ConvertTo(toKeyType);
var toValue = entry.Value.ConvertTo(toValueType);
d[toKey] = toValue;
}
}
else
{
foreach (var entry in values)
{
d[entry.Key] = entry.Value;
}
}
}
else
{
PopulateInstanceInternal(values, to, type);
}
return to;
}
public static void PopulateInstance(this IEnumerable<KeyValuePair<string, object>> values, object instance)
{
if (values == null || instance == null)
return;
PopulateInstanceInternal(values, instance, instance.GetType());
}
private static void PopulateInstanceInternal(IEnumerable<KeyValuePair<string, object>> values, object to, Type type)
{
if (!toObjectMapCache.TryGetValue(type, out var def))
toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type);
foreach (var entry in values)
{
if (!def.FieldsMap.TryGetValue(entry.Key, out var fieldDef) &&
!def.FieldsMap.TryGetValue(entry.Key.ToPascalCase(), out fieldDef)
|| entry.Value == null
|| entry.Value == DBNull.Value)
continue;
fieldDef.SetValue(to, entry.Value);
}
}
public static T FromObjectDictionary<T>(this IEnumerable<KeyValuePair<string, object>> values)
{
return (T)values.FromObjectDictionary(typeof(T));
}
private static ObjectDictionaryDefinition CreateObjectDictionaryDefinition(Type type)
{
var def = new ObjectDictionaryDefinition
{
Type = type,
};
foreach (var pi in type.GetSerializableProperties())
{
def.Add(pi.Name, new ObjectDictionaryFieldDefinition
{
Name = pi.Name,
Type = pi.PropertyType,
GetValueFn = pi.CreateGetter(),
SetValueFn = pi.CreateSetter(),
});
}
if (JsConfig.IncludePublicFields)
{
foreach (var fi in type.GetSerializableFields())
{
def.Add(fi.Name, new ObjectDictionaryFieldDefinition
{
Name = fi.Name,
Type = fi.FieldType,
GetValueFn = fi.CreateGetter(),
SetValueFn = fi.CreateSetter(),
});
}
}
return def;
}
public static Dictionary<string, object> ToSafePartialObjectDictionary<T>(this T instance)
{
var to = new Dictionary<string, object>();
var propValues = instance.ToObjectDictionary();
if (propValues != null)
{
foreach (var entry in propValues)
{
var valueType = entry.Value?.GetType();
try
{
if (valueType == null || !valueType.IsClass || valueType == typeof(string))
{
to[entry.Key] = entry.Value;
}
else if (!TypeSerializer.HasCircularReferences(entry.Value))
{
if (entry.Value is IEnumerable enumerable)
{
to[entry.Key] = entry.Value;
}
else
{
to[entry.Key] = entry.Value.ToSafePartialObjectDictionary();
}
}
else
{
to[entry.Key] = entry.Value.ToString();
}
}
catch (Exception ignore)
{
Tracer.Instance.WriteDebug($"Could not retrieve value from '{valueType?.GetType().Name}': ${ignore.Message}");
}
}
}
return to;
}
public static Dictionary<string, object> MergeIntoObjectDictionary(this object obj, params object[] sources)
{
var to = obj.ToObjectDictionary();
foreach (var source in sources)
foreach (var entry in source.ToObjectDictionary())
{
to[entry.Key] = entry.Value;
}
return to;
}
public static Dictionary<string, string> ToStringDictionary(this IEnumerable<KeyValuePair<string, object>> from) => ToStringDictionary(from, null);
public static Dictionary<string, string> ToStringDictionary(this IEnumerable<KeyValuePair<string, object>> from, IEqualityComparer<string> comparer)
{
var to = comparer != null
? new Dictionary<string, string>(comparer)
: new Dictionary<string, string>();
if (from != null)
{
foreach (var entry in from)
{
to[entry.Key] = entry.Value is string s
? s
: entry.Value.ConvertTo<string>();
}
}
return to;
}
}
}