ReflectionCollectionBuilder
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.ClientModel.Primitives
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("This class uses reflection. Pass in a generated ModelReaderWriterContext to be AOT compatible.")]
internal class ReflectionCollectionBuilder : ModelReaderWriterTypeBuilder
{
private Type _collectionType;
private string _addMethod;
protected override Type BuilderType => _collectionType;
[System.Runtime.CompilerServices.Nullable(2)]
protected override Type ItemType {
[System.Runtime.CompilerServices.NullableContext(2)]
get {
return _collectionType.GetGenericArguments()[0];
}
}
public ReflectionCollectionBuilder(Type collectionType, string addMethod = "Add")
{
_collectionType = collectionType;
_addMethod = addMethod;
}
protected override object CreateInstance()
{
return Activator.CreateInstance(_collectionType);
}
protected override void AddItem(object collection, [System.Runtime.CompilerServices.Nullable(2)] object item)
{
_collectionType.GetMethod(_addMethod, new Type[1] {
ItemType
}).Invoke(collection, new object[1] {
item
});
}
}
}