好吧,我对 这个答案 有一点儿迷恋,所以我必须分享一下我添加的抽象工厂来支持我的构造函数注入。
using System;
using System.Collections.ObjectModel;
namespace MVVM
{
public class ObservableVMCollectionFactory<TModel, TViewModel>
: IVMCollectionFactory<TModel, TViewModel>
where TModel : class
where TViewModel : class
{
private readonly IVMFactory<TModel, TViewModel> _factory;
public ObservableVMCollectionFactory( IVMFactory<TModel, TViewModel> factory )
{
this._factory = factory.CheckForNull();
}
public ObservableCollection<TViewModel> CreateVMCollectionFrom( ObservableCollection<TModel> models )
{
Func<TModel, TViewModel> viewModelCreator = model => this._factory.CreateVMFrom(model);
return new ObservableVMCollection<TViewModel, TModel>(models, viewModelCreator);
}
}
}
这是基于这个构建的:
using System.Collections.ObjectModel;
namespace MVVM
{
public interface IVMCollectionFactory<TModel, TViewModel>
where TModel : class
where TViewModel : class
{
ObservableCollection<TViewModel> CreateVMCollectionFrom( ObservableCollection<TModel> models );
}
}
还有这个:
namespace MVVM
{
public interface IVMFactory<TModel, TViewModel>
{
TViewModel CreateVMFrom( TModel model );
}
}
以下是用于完整性检查的空值检查器:
namespace System
{
public static class Exceptions
{
public static T CheckForNull<T>( this T thing, string message )
{
if ( thing == null ) throw new NullReferenceException(message);
return thing;
}
public static T CheckForNull<T>( this T thing )
{
if ( thing == null ) throw new NullReferenceException();
return thing;
}
}
}