I have the following base class which is abstract:
public abstract class MasterDataViewModel<TPrimaryModel> : ViewModel
where TPrimaryModel : TwoNames, new()
{
...
}
I have some derived classes like:
public class ConsignorViewModel : MasterDataViewModel<Consignor>
{
protected override void Find()
{
...
foreach (Consignor consignor in consignors)
{
ConsignorViewModel viewModel = new ConsignorViewModel(consignor, consignor.Address);
SearchResults.Add(viewModel);
}
...
}
}
I would like to move the Find method to my base class. The problem is the constructor call which is not possible in my abstract class. It has to be something like this:
protected override void Find()
{
...
foreach (TPrimaryModel primaryModel in results)
{
MasterDataViewModel<TPrimaryModel> viewModel = new MasterDataViewModel(primaryModel, primaryModel.Address);
SearchResults.Add(viewModel);
}
...
}
It's not working as constructor calls in abstract classes are not allowed. Any other solution? I thought about another generic. Problem is that a new constraint cannot have any parameters so this doesn't work, too.
Either create an abstract method in the base class "CreateViewModel" that you override in each model. Or use the Activator.CreateInstance method to create an instance of the this.GetType() subclass.
The first one is the cleanest. That way your class serves as a factory for itself.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments