/
TypeDescriptor.cs
3805 lines (3364 loc) · 170 KB
/
TypeDescriptor.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 MIT license.
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.ComponentModel
{
/// <summary>
/// Provides information about the properties and events for a component.
/// This class cannot be inherited.
/// </summary>
public sealed class TypeDescriptor
{
internal const DynamicallyAccessedMemberTypes ReflectTypesDynamicallyAccessedMembers = DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields;
internal const string EditorRequiresUnreferencedCode = "Editors registered in TypeDescriptor.AddEditorTable may be trimmed.";
// Note: this is initialized at class load because we
// lock on it for thread safety. It is used from nearly
// every call to this class, so it will be created soon after
// class load anyway.
private static readonly WeakHashtable s_providerTable = new WeakHashtable(); // mapping of type or object hash to a provider list
private static readonly Hashtable s_providerTypeTable = new Hashtable(); // A direct mapping from type to provider.
private static readonly Hashtable s_defaultProviderInitialized = new Hashtable(); // A table of type -> object to track DefaultTypeDescriptionProviderAttributes.
// A value of `null` indicates initialization is in progress.
// A value of s_initializedDefaultProvider indicates the provider is initialized.
private static readonly object s_initializedDefaultProvider = new object();
private static WeakHashtable? s_associationTable;
private static int s_metadataVersion; // a version stamp for our metadata. Used by property descriptors to know when to rebuild attributes.
// This is an index that we use to create a unique name for a property in the
// event of a name collision. The only time we should use this is when
// a name collision happened on an extender property that has no site or
// no name on its site. Should be very rare.
private static int s_collisionIndex;
// For each stage of our filtering pipeline, the pipeline needs to know what it is filtering.
private const int PIPELINE_ATTRIBUTES = 0x00;
private const int PIPELINE_PROPERTIES = 0x01;
private const int PIPELINE_EVENTS = 0x02;
// And each stage of the pipeline needs to have its own
// keys for its cache table. We use guids because they
// are unique and fast to compare. The order for each of
// these keys must match the Id's of the filter type above.
private static readonly Guid[] s_pipelineInitializeKeys = new Guid[]
{
Guid.NewGuid(), // attributes
Guid.NewGuid(), // properties
Guid.NewGuid() // events
};
private static readonly Guid[] s_pipelineMergeKeys = new Guid[]
{
Guid.NewGuid(), // attributes
Guid.NewGuid(), // properties
Guid.NewGuid() // events
};
private static readonly Guid[] s_pipelineFilterKeys = new Guid[]
{
Guid.NewGuid(), // attributes
Guid.NewGuid(), // properties
Guid.NewGuid() // events
};
private static readonly Guid[] s_pipelineAttributeFilterKeys = new Guid[]
{
Guid.NewGuid(), // attributes
Guid.NewGuid(), // properties
Guid.NewGuid() // events
};
private TypeDescriptor()
{
}
/// <summary>
/// This property returns a Type object that can be passed to the various
/// AddProvider methods to define a type description provider for interface types.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static Type InterfaceType
{
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
get => typeof(TypeDescriptorInterface);
}
/// <summary>
/// This value increments each time someone refreshes or changes metadata.
/// </summary>
internal static int MetadataVersion => s_metadataVersion;
private static WeakHashtable AssociationTable => LazyInitializer.EnsureInitialized(ref s_associationTable, () => new WeakHashtable());
/// <summary>
/// Occurs when Refreshed is raised for a component.
/// </summary>
public static event RefreshEventHandler? Refreshed;
/// <summary>
/// The AddAttributes method allows you to add class-level attributes for a
/// type or an instance. This method simply implements a type description provider
/// that merges the provided attributes with the attributes that already exist on
/// the class. This is a short cut for such a behavior. Adding additional
/// attributes is common need for applications using the Windows Forms property
/// window. The return value form AddAttributes is the TypeDescriptionProvider
/// that was used to add the attributes. This provider can later be passed to
/// RemoveProvider if the added attributes are no longer needed.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static TypeDescriptionProvider AddAttributes(Type type, params Attribute[] attributes)
{
ArgumentNullException.ThrowIfNull(type);
ArgumentNullException.ThrowIfNull(attributes);
TypeDescriptionProvider existingProvider = GetProvider(type);
TypeDescriptionProvider provider = new AttributeProvider(existingProvider, attributes);
TypeDescriptor.AddProvider(provider, type);
return provider;
}
/// <summary>
/// The AddAttributes method allows you to add class-level attributes for a
/// type or an instance. This method simply implements a type description provider
/// that merges the provided attributes with the attributes that already exist on
/// the class. This is a short cut for such a behavior. Adding additional
/// attributes is common need for applications using the Windows Forms property
/// window. The return value form AddAttributes is the TypeDescriptionProvider
/// that was used to add the attributes. This provider can later be passed to
/// RemoveProvider if the added attributes are no longer needed.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static TypeDescriptionProvider AddAttributes(object instance, params Attribute[] attributes)
{
ArgumentNullException.ThrowIfNull(instance);
ArgumentNullException.ThrowIfNull(attributes);
TypeDescriptionProvider existingProvider = GetProvider(instance);
TypeDescriptionProvider provider = new AttributeProvider(existingProvider, attributes);
AddProvider(provider, instance);
return provider;
}
/// <summary>
/// Adds an editor table for the given editor base type. Typically, editors are
/// specified as metadata on an object. If no metadata for a requested editor
/// base type can be found on an object, however, the TypeDescriptor will search
/// an editor table for the editor type, if one can be found.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[RequiresUnreferencedCode("The Types specified in table may be trimmed, or have their static construtors trimmed.")]
public static void AddEditorTable(Type editorBaseType, Hashtable table)
{
ReflectTypeDescriptionProvider.AddEditorTable(editorBaseType, table);
}
/// <summary>
/// Adds a type description provider that will be called on to provide
/// type and instance information for any object that is of, or a subtype
/// of, the provided type. Type can be any type, including interfaces.
/// For example, to provide custom type and instance information for all
/// components, you would pass typeof(IComponent). Passing typeof(object)
/// will cause the provider to be called to provide type information for
/// all types.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static void AddProvider(TypeDescriptionProvider provider, Type type)
{
ArgumentNullException.ThrowIfNull(provider);
ArgumentNullException.ThrowIfNull(type);
lock (s_providerTable)
{
// Get the root node, hook it up, and stuff it back into
// the provider cache.
TypeDescriptionNode node = NodeFor(type, true);
var head = new TypeDescriptionNode(provider) { Next = node };
s_providerTable[type] = head;
s_providerTypeTable.Clear();
}
Refresh(type);
}
/// <summary>
/// Adds a type description provider that will be called on to provide
/// type information for a single object instance. A provider added
/// using this method will never have its CreateInstance method called
/// because the instance already exists. This method does not prevent
/// the object from finalizing.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static void AddProvider(TypeDescriptionProvider provider, object instance)
{
ArgumentNullException.ThrowIfNull(provider);
ArgumentNullException.ThrowIfNull(instance);
bool refreshNeeded;
// Get the root node, hook it up, and stuff it back into
// the provider cache.
lock (s_providerTable)
{
refreshNeeded = s_providerTable.ContainsKey(instance);
TypeDescriptionNode node = NodeFor(instance, true);
var head = new TypeDescriptionNode(provider) { Next = node };
s_providerTable.SetWeak(instance, head);
s_providerTypeTable.Clear();
}
if (refreshNeeded)
{
Refresh(instance, false);
}
}
/// <summary>
/// Adds a type description provider that will be called on to provide
/// type and instance information for any object that is of, or a subtype
/// of, the provided type. Type can be any type, including interfaces.
/// For example, to provide custom type and instance information for all
/// components, you would pass typeof(IComponent). Passing typeof(object)
/// will cause the provider to be called to provide type information for
/// all types.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static void AddProviderTransparent(TypeDescriptionProvider provider, Type type)
{
ArgumentNullException.ThrowIfNull(provider);
ArgumentNullException.ThrowIfNull(type);
AddProvider(provider, type);
}
/// <summary>
/// Adds a type description provider that will be called on to provide
/// type information for a single object instance. A provider added
/// using this method will never have its CreateInstance method called
/// because the instance already exists. This method does not prevent
/// the object from finalizing.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static void AddProviderTransparent(TypeDescriptionProvider provider, object instance)
{
ArgumentNullException.ThrowIfNull(provider);
ArgumentNullException.ThrowIfNull(instance);
AddProvider(provider, instance);
}
/// <summary>
/// This method verifies that we have checked for the presence
/// of a default type description provider attribute for the
/// given type.
/// </summary>
private static void CheckDefaultProvider(Type type)
{
if (s_defaultProviderInitialized[type] == s_initializedDefaultProvider)
{
return;
}
// Lock on s_providerTable even though s_providerTable is not modified here.
// Using a single lock prevents deadlocks since other methods that call into or are called
// by this method also lock on s_providerTable and the ordering of the locks may be different.
lock (s_providerTable)
{
AddDefaultProvider(type);
}
}
/// <summary>
/// Add the default provider, if it exists.
/// For threading, this is always called under a 'lock (s_providerTable)'.
/// </summary>
private static void AddDefaultProvider(Type type)
{
bool providerAdded = false;
if (s_defaultProviderInitialized.ContainsKey(type))
{
// Either another thread finished initializing for this type, or we are recursing on the same thread.
return;
}
// Immediately set this to null to indicate we are in progress setting the default provider for a type.
// This prevents re-entrance to this method.
s_defaultProviderInitialized[type] = null;
// Always use core reflection when checking for the default provider attribute.
// If there is a provider, we probably don't want to build up our own cache state against the type.
// There shouldn't be more than one of these, but walk anyway.
// Walk in reverse order so that the most derived takes precedence.
object[] attrs = type.GetCustomAttributes(typeof(TypeDescriptionProviderAttribute), false);
for (int idx = attrs.Length - 1; idx >= 0; idx--)
{
TypeDescriptionProviderAttribute pa = (TypeDescriptionProviderAttribute)attrs[idx];
Type? providerType = Type.GetType(pa.TypeName);
if (providerType != null && typeof(TypeDescriptionProvider).IsAssignableFrom(providerType))
{
TypeDescriptionProvider prov = (TypeDescriptionProvider)Activator.CreateInstance(providerType)!;
AddProvider(prov, type);
providerAdded = true;
}
}
// If we did not add a provider, check the base class.
if (!providerAdded)
{
Type? baseType = type.BaseType;
if (baseType != null && baseType != type)
{
AddDefaultProvider(baseType);
}
}
s_defaultProviderInitialized[type] = s_initializedDefaultProvider;
}
/// <summary>
/// The CreateAssociation method creates an association between two objects.
/// Once an association is created, a designer or other filtering mechanism
/// can add properties that route to either object into the primary object's
/// property set. When a property invocation is made against the primary
/// object, GetAssociation will be called to resolve the actual object
/// instance that is related to its type parameter.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static void CreateAssociation(object primary, object secondary)
{
ArgumentNullException.ThrowIfNull(primary);
ArgumentNullException.ThrowIfNull(secondary);
if (primary == secondary)
{
throw new ArgumentException(SR.TypeDescriptorSameAssociation);
}
WeakHashtable associationTable = AssociationTable;
IList? associations = (IList?)associationTable[primary];
if (associations == null)
{
lock (associationTable)
{
associations = (IList?)associationTable[primary];
if (associations == null)
{
associations = new ArrayList(4);
associationTable.SetWeak(primary, associations);
}
}
}
else
{
for (int idx = associations.Count - 1; idx >= 0; idx--)
{
WeakReference r = (WeakReference)associations[idx]!;
if (r.IsAlive && r.Target == secondary)
{
throw new ArgumentException(SR.TypeDescriptorAlreadyAssociated);
}
}
}
lock (associations)
{
associations.Add(new WeakReference(secondary));
}
}
/// <summary>
/// This dynamically binds an EventDescriptor to a type.
/// </summary>
public static EventDescriptor CreateEvent(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType,
string name,
Type type,
params Attribute[] attributes)
{
return new ReflectEventDescriptor(componentType, name, type, attributes);
}
/// <summary>
/// This creates a new event descriptor identical to an existing event descriptor. The new event descriptor
/// has the specified metadata attributes merged with the existing metadata attributes.
/// </summary>
public static EventDescriptor CreateEvent(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType,
EventDescriptor oldEventDescriptor,
params Attribute[] attributes)
{
return new ReflectEventDescriptor(componentType, oldEventDescriptor, attributes);
}
/// <summary>
/// This method will search internal tables within TypeDescriptor for
/// a TypeDescriptionProvider object that is associated with the given
/// data type. If it finds one, it will delegate the call to that object.
/// </summary>
public static object? CreateInstance(
IServiceProvider? provider,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type objectType,
Type[]? argTypes,
object?[]? args)
{
ArgumentNullException.ThrowIfNull(objectType);
if (argTypes != null)
{
ArgumentNullException.ThrowIfNull(args);
if (argTypes.Length != args.Length)
{
throw new ArgumentException(SR.TypeDescriptorArgsCountMismatch);
}
}
object? instance = null;
// See if the provider wants to offer a TypeDescriptionProvider to delegate to. This allows
// a caller to have complete control over all object instantiation.
if (provider?.GetService(typeof(TypeDescriptionProvider)) is TypeDescriptionProvider p)
{
instance = p.CreateInstance(provider, objectType, argTypes, args);
}
return instance ?? NodeFor(objectType).CreateInstance(provider, objectType, argTypes, args);
}
/// <summary>
/// This dynamically binds a PropertyDescriptor to a type.
/// </summary>
[RequiresUnreferencedCode(PropertyDescriptor.PropertyDescriptorPropertyTypeMessage)]
public static PropertyDescriptor CreateProperty(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType,
string name,
Type type,
params Attribute[] attributes)
{
return new ReflectPropertyDescriptor(componentType, name, type, attributes);
}
/// <summary>
/// This creates a new property descriptor identical to an existing property descriptor. The new property descriptor
/// has the specified metadata attributes merged with the existing metadata attributes.
/// </summary>
[RequiresUnreferencedCode(PropertyDescriptor.PropertyDescriptorPropertyTypeMessage)]
public static PropertyDescriptor CreateProperty(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType,
PropertyDescriptor oldPropertyDescriptor,
params Attribute[] attributes)
{
// We must do some special case work here for extended properties. If the old property descriptor is really
// an extender property that is being surfaced on a component as a normal property, then we must
// do work here or else ReflectPropertyDescriptor will fail to resolve the get and set methods. We check
// for the necessary ExtenderProvidedPropertyAttribute and if we find it, we create an
// ExtendedPropertyDescriptor instead. We only do this if the component class is the same, since the user
// may want to re-route the property to a different target.
//
if (componentType == oldPropertyDescriptor.ComponentType)
{
ExtenderProvidedPropertyAttribute attr = (ExtenderProvidedPropertyAttribute)
oldPropertyDescriptor.Attributes[
typeof(ExtenderProvidedPropertyAttribute)]!;
if (attr.ExtenderProperty is ReflectPropertyDescriptor)
{
return new ExtendedPropertyDescriptor(oldPropertyDescriptor, attributes);
}
}
// This is either a normal prop or the caller has changed target classes.
return new ReflectPropertyDescriptor(componentType, oldPropertyDescriptor, attributes);
}
/// <summary>
/// This API is used to remove any members from the given
/// collection that do not match the attribute array. If members
/// need to be removed, a new ArrayList wil be created that
/// contains only the remaining members. The API returns
/// NULL if it did not need to filter any members.
/// </summary>
[RequiresUnreferencedCode(AttributeCollection.FilterRequiresUnreferencedCodeMessage)]
private static ArrayList? FilterMembers(IList members, Attribute[] attributes)
{
ArrayList? newMembers = null;
int memberCount = members.Count;
for (int idx = 0; idx < memberCount; idx++)
{
bool hide = false;
for (int attrIdx = 0; attrIdx < attributes.Length; attrIdx++)
{
if (ShouldHideMember((MemberDescriptor?)members[idx], attributes[attrIdx]))
{
hide = true;
break;
}
}
if (hide)
{
// We have to hide. If this is the first time, we need to init
// newMembers to have all the valid members we have previously
// hit.
if (newMembers == null)
{
newMembers = new ArrayList(memberCount);
for (int validIdx = 0; validIdx < idx; validIdx++)
{
newMembers.Add(members[validIdx]);
}
}
}
else
{
newMembers?.Add(members[idx]);
}
}
return newMembers;
}
/// <summary>
/// The GetAssociation method returns the correct object to invoke
/// for the requested type. It never returns null.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static object GetAssociation(Type type, object primary)
{
ArgumentNullException.ThrowIfNull(type);
ArgumentNullException.ThrowIfNull(primary);
object associatedObject = primary;
if (!type.IsInstanceOfType(primary))
{
// Check our association table for a match.
Hashtable assocTable = AssociationTable;
IList? associations = (IList?)assocTable?[primary];
if (associations != null)
{
lock (associations)
{
for (int idx = associations.Count - 1; idx >= 0; idx--)
{
// Look for an associated object that has a type that
// matches the given type.
WeakReference weakRef = (WeakReference)associations[idx]!;
object? secondary = weakRef.Target;
if (secondary == null)
{
associations.RemoveAt(idx);
}
else if (type.IsInstanceOfType(secondary))
{
associatedObject = secondary;
}
}
}
}
// Not in our table. We have a default association with a designer
// if that designer is a component.
if (associatedObject == primary)
{
IComponent? component = primary as IComponent;
if (component != null)
{
ISite? site = component.Site;
if (site != null && site.DesignMode)
{
IDesignerHost? host = site.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host != null)
{
object? designer = host.GetDesigner(component);
// We only use the designer if it has a compatible class. If we
// got here, we're probably hosed because the user just passed in
// an object that this PropertyDescriptor can't munch on, but it's
// clearer to use that object instance instead of it's designer.
if (designer != null && type.IsInstanceOfType(designer))
{
associatedObject = designer;
}
}
}
}
}
}
return associatedObject;
}
/// <summary>
/// Gets a collection of attributes for the specified type of component.
/// </summary>
public static AttributeCollection GetAttributes([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType)
{
if (componentType == null)
{
Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here");
return new AttributeCollection((Attribute[])null);
}
AttributeCollection attributes = GetDescriptor(componentType, nameof(componentType)).GetAttributes();
return attributes;
}
/// <summary>
/// Gets a collection of attributes for the specified component.
/// </summary>
[RequiresUnreferencedCode("The Type of component cannot be statically discovered.")]
public static AttributeCollection GetAttributes(object component)
{
return GetAttributes(component, false);
}
/// <summary>
/// Gets a collection of attributes for the specified component.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[RequiresUnreferencedCode("The Type of component cannot be statically discovered.")]
public static AttributeCollection GetAttributes(object component, bool noCustomTypeDesc)
{
if (component == null)
{
Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here");
return new AttributeCollection(null);
}
// We create a sort of pipeline for mucking with metadata. The pipeline
// goes through the following process:
//
// 1. Merge metadata from extenders.
// 2. Allow services to filter the metadata
// 3. If an attribute filter was specified, apply that.
//
// The goal here is speed. We get speed by not copying or
// allocating memory. We do this by allowing each phase of the
// pipeline to cache its data in the object cache. If
// a phase makes a change to the results, this change must cause
// successive phases to recompute their results as well. "Results" is
// always a collection, and the various stages of the pipeline may
// replace or modify this collection (depending on if it's a
// read-only IList or not). It is possible for the original
// descriptor or attribute collection to pass through the entire
// pipeline without modification.
//
ICustomTypeDescriptor typeDesc = GetDescriptor(component, noCustomTypeDesc)!;
ICollection results = typeDesc.GetAttributes();
// If we are handed a custom type descriptor we have several choices of action
// we can take. If noCustomTypeDesc is true, it means that the custom type
// descriptor is trying to find a baseline set of properties. In this case
// we should merge in extended properties, but we do not let designers filter
// because we're not done with the property set yet. If noCustomTypeDesc
// is false, we don't do extender properties because the custom type descriptor
// has already added them. In this case, we are doing a final pass so we
// want to apply filtering. Finally, if the incoming object is not a custom
// type descriptor, we do extenders and the filter.
//
if (component is ICustomTypeDescriptor)
{
if (noCustomTypeDesc)
{
ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component);
if (extDesc != null)
{
ICollection extResults = extDesc.GetAttributes();
results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, null);
}
}
else
{
results = PipelineFilter(PIPELINE_ATTRIBUTES, results, component, null);
}
}
else
{
IDictionary? cache = GetCache(component);
results = PipelineInitialize(PIPELINE_ATTRIBUTES, results, cache);
ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component);
if (extDesc != null)
{
ICollection extResults = extDesc.GetAttributes();
results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, cache);
}
results = PipelineFilter(PIPELINE_ATTRIBUTES, results, component, cache);
}
if (!(results is AttributeCollection attrs))
{
Attribute[] attrArray = new Attribute[results.Count];
results.CopyTo(attrArray, 0);
attrs = new AttributeCollection(attrArray);
}
return attrs;
}
/// <summary>
/// Helper function to obtain a cache for the given object.
/// </summary>
internal static IDictionary? GetCache(object instance) => NodeFor(instance).GetCache(instance);
/// <summary>
/// Gets the name of the class for the specified component.
/// </summary>
[RequiresUnreferencedCode("The Type of component cannot be statically discovered.")]
public static string? GetClassName(object component) => GetClassName(component, false);
/// <summary>
/// Gets the name of the class for the specified component.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[RequiresUnreferencedCode("The Type of component cannot be statically discovered.")]
public static string? GetClassName(object component, bool noCustomTypeDesc)
{
return GetDescriptor(component, noCustomTypeDesc)!.GetClassName();
}
/// <summary>
/// Gets the name of the class for the specified type.
/// </summary>
public static string? GetClassName(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType)
{
return GetDescriptor(componentType, nameof(componentType)).GetClassName();
}
/// <summary>
/// The name of the class for the specified component.
/// </summary>
[RequiresUnreferencedCode("The Type of component cannot be statically discovered.")]
public static string? GetComponentName(object component) => GetComponentName(component, false);
/// <summary>
/// Gets the name of the class for the specified component.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[RequiresUnreferencedCode("The Type of component cannot be statically discovered.")]
public static string? GetComponentName(object component, bool noCustomTypeDesc)
{
return GetDescriptor(component, noCustomTypeDesc)!.GetComponentName();
}
/// <summary>
/// Gets a type converter for the type of the specified component.
/// </summary>
[RequiresUnreferencedCode(TypeConverter.RequiresUnreferencedCodeMessage + " The Type of component cannot be statically discovered.")]
public static TypeConverter GetConverter(object component) => GetConverter(component, false);
/// <summary>
/// Gets a type converter for the type of the specified component.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[RequiresUnreferencedCode(TypeConverter.RequiresUnreferencedCodeMessage + " The Type of component cannot be statically discovered.")]
public static TypeConverter GetConverter(object component, bool noCustomTypeDesc)
{
TypeConverter? converter = GetDescriptor(component, noCustomTypeDesc)!.GetConverter();
// GetDescriptor will only return DefaultTypeDescriptor, or MergedTypeDescriptor with DefaultTypeDescriptor as the secondary,
// which will always return a non-null TypeConverter.
Debug.Assert(converter != null, "Unexpected null TypeConverter.");
return converter;
}
/// <summary>
/// Gets a type converter for the specified type.
/// </summary>
[RequiresUnreferencedCode(TypeConverter.RequiresUnreferencedCodeMessage)]
public static TypeConverter GetConverter([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type)
{
return GetDescriptor(type, nameof(type)).GetConverter();
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "The callers of this method ensure getting the converter is trim compatible - i.e. the type is not Nullable<T>.")]
internal static TypeConverter GetConverterTrimUnsafe([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) =>
GetConverter(type);
// This is called by System.ComponentModel.DefaultValueAttribute via reflection.
[RequiresUnreferencedCode(TypeConverter.RequiresUnreferencedCodeMessage)]
private static object? ConvertFromInvariantString([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, string stringValue)
{
return GetConverter(type).ConvertFromInvariantString(stringValue);
}
/// <summary>
/// Gets the default event for the specified type of component.
/// </summary>
[RequiresUnreferencedCode(EventDescriptor.RequiresUnreferencedCodeMessage)]
public static EventDescriptor? GetDefaultEvent(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType)
{
if (componentType == null)
{
Debug.Fail("COMPAT: Returning null, but you should not pass null here");
return null;
}
return GetDescriptor(componentType, nameof(componentType)).GetDefaultEvent();
}
/// <summary>
/// Gets the default event for the specified component.
/// </summary>
[RequiresUnreferencedCode(EventDescriptor.RequiresUnreferencedCodeMessage + " The Type of component cannot be statically discovered.")]
public static EventDescriptor? GetDefaultEvent(object component) => GetDefaultEvent(component, false);
/// <summary>
/// Gets the default event for a component.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[RequiresUnreferencedCode(EventDescriptor.RequiresUnreferencedCodeMessage + " The Type of component cannot be statically discovered.")]
public static EventDescriptor? GetDefaultEvent(object component, bool noCustomTypeDesc)
{
if (component == null)
{
Debug.Fail("COMPAT: Returning null, but you should not pass null here");
return null;
}
return GetDescriptor(component, noCustomTypeDesc)!.GetDefaultEvent();
}
/// <summary>
/// Gets the default property for the specified type of component.
/// </summary>
[RequiresUnreferencedCode(PropertyDescriptor.PropertyDescriptorPropertyTypeMessage)]
public static PropertyDescriptor? GetDefaultProperty(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType)
{
if (componentType == null)
{
Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here");
return null;
}
return GetDescriptor(componentType, nameof(componentType)).GetDefaultProperty();
}
/// <summary>
/// Gets the default property for the specified component.
/// </summary>
[RequiresUnreferencedCode(PropertyDescriptor.PropertyDescriptorPropertyTypeMessage + " The Type of component cannot be statically discovered.")]
public static PropertyDescriptor? GetDefaultProperty(object component) => GetDefaultProperty(component, false);
/// <summary>
/// Gets the default property for the specified component.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[RequiresUnreferencedCode(PropertyDescriptor.PropertyDescriptorPropertyTypeMessage + " The Type of component cannot be statically discovered.")]
public static PropertyDescriptor? GetDefaultProperty(object component, bool noCustomTypeDesc)
{
if (component == null)
{
Debug.Fail("COMPAT: Returning null, but you should not pass null here");
return null;
}
return GetDescriptor(component, noCustomTypeDesc)!.GetDefaultProperty();
}
/// <summary>
/// Returns a custom type descriptor for the given type.
/// Performs arg checking so callers don't have to.
/// </summary>
private static DefaultTypeDescriptor GetDescriptor(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type,
string typeName)
{
ArgumentNullException.ThrowIfNull(type, typeName);
return NodeFor(type).GetDefaultTypeDescriptor(type);
}
/// <summary>
/// Returns a custom type descriptor for the given instance.
/// Performs arg checking so callers don't have to. This
/// will call through to instance if it is a custom type
/// descriptor.
/// </summary>
[RequiresUnreferencedCode("The Type of component cannot be statically discovered.")]
internal static ICustomTypeDescriptor? GetDescriptor(object component, bool noCustomTypeDesc)
{
if (component == null)
{
throw new ArgumentException(nameof(component));
}
ICustomTypeDescriptor? desc = NodeFor(component).GetTypeDescriptor(component);
ICustomTypeDescriptor? d = component as ICustomTypeDescriptor;
if (!noCustomTypeDesc && d != null)
{
desc = new MergedTypeDescriptor(d, desc!);
}
return desc;
}
/// <summary>
/// Returns an extended custom type descriptor for the given instance.
/// </summary>
[RequiresUnreferencedCode("The Type of component cannot be statically discovered.")]
internal static ICustomTypeDescriptor GetExtendedDescriptor(object component)
{
if (component == null)
{
throw new ArgumentException(nameof(component));
}
return NodeFor(component).GetExtendedTypeDescriptor(component);
}
/// <summary>
/// Gets an editor with the specified base type for the
/// specified component.
/// </summary>
[RequiresUnreferencedCode(EditorRequiresUnreferencedCode + " The Type of component cannot be statically discovered.")]
public static object? GetEditor(object component, Type editorBaseType)
{
return GetEditor(component, editorBaseType, false);
}
/// <summary>
/// Gets an editor with the specified base type for the
/// specified component.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[RequiresUnreferencedCode(EditorRequiresUnreferencedCode + " The Type of component cannot be statically discovered.")]
public static object? GetEditor(object component, Type editorBaseType, bool noCustomTypeDesc)
{
ArgumentNullException.ThrowIfNull(editorBaseType);
return GetDescriptor(component, noCustomTypeDesc)!.GetEditor(editorBaseType);
}
/// <summary>
/// Gets an editor with the specified base type for the specified type.
/// </summary>
[RequiresUnreferencedCode(EditorRequiresUnreferencedCode)]
public static object? GetEditor(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type,
Type editorBaseType)
{
ArgumentNullException.ThrowIfNull(editorBaseType);
return GetDescriptor(type, nameof(type)).GetEditor(editorBaseType);
}
/// <summary>
/// Gets a collection of events for a specified type of component.
/// </summary>
public static EventDescriptorCollection GetEvents(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType)
{
if (componentType == null)
{
Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here");
return new EventDescriptorCollection(null, true);
}
return GetDescriptor(componentType, nameof(componentType))!.GetEvents();
}
/// <summary>
/// Gets a collection of events for a specified type of
/// component using a specified array of attributes as a filter.
/// </summary>
[RequiresUnreferencedCode(AttributeCollection.FilterRequiresUnreferencedCodeMessage)]
public static EventDescriptorCollection GetEvents(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentType,
Attribute[] attributes)
{
if (componentType == null)
{
Debug.Fail("COMPAT: Returning an empty collection, but you should not pass null here");
return new EventDescriptorCollection(null, true);
}
EventDescriptorCollection events = GetDescriptor(componentType, nameof(componentType)).GetEvents(attributes);
if (attributes != null && attributes.Length > 0)