Good day, faced with such a problem. There is an abstract ViewModel class that contains the logic for adding data to the collection for display in the GUI.
public abstract class ViewModel { public ObservableCollection<IModel> Data { get; set; } protected abstract IModel createObject(SqlDataReader reader); protected void selectData(string query) { // ... // ΠΠΎΠ³ΠΈΠΊΠ° ΠΏΠΎΠ»ΡΡΠ΅Π½ΠΈΡ reader // ... IModel item = this.createObject(reader); this.Data.Add(item); } } There are also classes of models, all of them implement the IModel interface, I will not give the code, there is no need for it. The class implementing ViewModel looks like this:
public class UsersViewModel : ViewModel { public UsersViewModel() { string query = "SELECT TOP 300 * FROM users ORDER BY reputation DESC"; this.selectData(query); } protected override IModel createObject(SqlDataReader reader) { return new User(reader); } } The problem is actually in the createObject method. In all subclasses, it does one single thing: it returns an instance of the model class. I would like to get rid of him. And to make it so that in the abstract class ViewModel the selectData method itself created the model object it needed, and which one it would learn from the subclass. The method should look something like this:
protected void selectData(string query) { // ΠΠΎΠ³ΠΈΠΊΠ° ΠΏΠΎΠ»ΡΡΠ΅Π½ΠΈΡ reader IModel item = new Π’ΠΈΠΏ_ΠΠΎΠ΄Π΅Π»ΠΈ_ΠΈΠ·_ΠΏΠΎΠ΄ΠΊΠ»Π°ΡΡΠ°(reader); this.Data.Add(item); } It seems to me that the problem can be solved with the help of generalizations, but I do not know how. Or create a property in the subclass that will specify which particular implementation of the IModel interface IModel be used. How do I implement this? Thank you in advance.