Skip to content

Commit aed4040

Browse files
authored
Merge pull request #622 from Microsoft/IncrementalLoadingCollection-Mod
Remove TSource default constructor requirement for IncrementalLoadingCollection
2 parents 4b7f30e + 7e686e1 commit aed4040

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

Microsoft.Toolkit.Uwp/IncrementalLoadingCollection/IncrementalLoadingCollection.cs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
using System.Collections.ObjectModel;
1616
using System.ComponentModel;
1717
using System.Linq;
18+
using System.Reflection;
1819
using System.Runtime.InteropServices.WindowsRuntime;
1920
using System.Threading;
2021
using System.Threading.Tasks;
@@ -38,7 +39,7 @@ namespace Microsoft.Toolkit.Uwp
3839
/// <seealso cref="ISupportIncrementalLoading"/>
3940
public class IncrementalLoadingCollection<TSource, IType> : ObservableCollection<IType>,
4041
ISupportIncrementalLoading
41-
where TSource : IIncrementalSource<IType>, new()
42+
where TSource : IIncrementalSource<IType>
4243
{
4344
/// <summary>
4445
/// Gets a value indicating the source of incremental loading.
@@ -134,7 +135,7 @@ private set
134135
/// </param>
135136
/// <seealso cref="IIncrementalSource{TSource}"/>
136137
public IncrementalLoadingCollection(int itemsPerPage = 20, Action onStartLoading = null, Action onEndLoading = null, Action<Exception> onError = null)
137-
: this(new TSource(), itemsPerPage, onStartLoading, onEndLoading, onError)
138+
: this(InstantiateSourceByReflection(), itemsPerPage, onStartLoading, onEndLoading, onError)
138139
{
139140
}
140141

@@ -159,6 +160,11 @@ public IncrementalLoadingCollection(int itemsPerPage = 20, Action onStartLoading
159160
/// <seealso cref="IIncrementalSource{TSource}"/>
160161
public IncrementalLoadingCollection(TSource source, int itemsPerPage = 20, Action onStartLoading = null, Action onEndLoading = null, Action<Exception> onError = null)
161162
{
163+
if (source == null)
164+
{
165+
throw new ArgumentNullException(nameof(source));
166+
}
167+
162168
Source = source;
163169

164170
_onStartLoading = onStartLoading;
@@ -196,6 +202,18 @@ protected virtual async Task<IEnumerable<IType>> LoadDataAsync(CancellationToken
196202
return result;
197203
}
198204

205+
private static TSource InstantiateSourceByReflection()
206+
{
207+
var type = typeof(TSource);
208+
ConstructorInfo constructor = type.GetConstructor(new Type[0]);
209+
if (constructor == null)
210+
{
211+
throw new InvalidOperationException("TSource must have a parameterless constructor");
212+
}
213+
214+
return (TSource)constructor.Invoke(null);
215+
}
216+
199217
private async Task<LoadMoreItemsResult> LoadMoreItemsAsync(uint count, CancellationToken cancellationToken)
200218
{
201219
uint resultCount = 0;

0 commit comments

Comments
 (0)