C# generics type resolving
I am writing a popup window service in for our mvvm application.
I have wrote this method in the popup controller
void ShowDialogWithResult<TVie开发者_如何学JAVAw, TViewModel, TResult>(Action<TResult, WindowClosedEventArgs> callbackAction)
where TView : FrameworkElement, IPopupContent<TViewModel>
where TViewModel : IResultViewModel<TResult>;
As you can see to show a popup window with view model and result the view must implement IPopupContent<TViewModel>
interface, and in its turn the view model must implement interface IResultViewModel<TResult>
So we have a chain of types started from TView->TViewModel->TResult
the call to such method looks like this:
_childWindowController
.ShowDialogWithResult<AddNationalityPopup,AddNationalityPopupModel, AddNationalityResult>(
(result, a) =>
{
if (a.DialogResult.HasValue && a.DialogResult.Value)
{
if (result.NationalityCountryId.HasValue)
{
Background.NationalityCountryId = result.NationalityCountryId.Value;
Background.NationalityDescription = result.NationalityDescription;
}
}
});
As you can see I am forced to pass all three type parameters for compiler to generate correct method.
And this code makes me sad. How can I reduce the amount of type parameters required by the call and still get type safety. I can't develop any valid solution.
There's no way of reducing these generic type parameters in this call, but you can use inheritance in order to specialize it overloading this method.
For example, if there're a lot of calls to .ShowDialogWithResult<AddNationalityPopup,AddNationalityPopupModel, ...>
, you can inherit your controller and add an overload like .ShowDialogWithResult<TResult>
.
Take 2:
Another approach like this would be adding these method's generic type parameters to the controller class and using inversion of control, it can be instantiated with the appropiate type arguments freeing the caller of providing them in .ShowDialogWithResult(...)
.
精彩评论