Могу ли я объединить конструкторы в С#
У меня есть следующий код:
public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID)
{
this._modelState = modelStateDictionary;
this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID);
this._productRepository = StorageHelper.GetTable<Product>(dataSourceID);
}
public AccountService(string dataSourceID)
{
this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID);
this._productRepository = StorageHelper.GetTable<Product>(dataSourceID);
}
Есть ли способ упростить конструкторы, чтобы каждый из них не выполнял вызовы StorageHelper?
Также мне нужно указать это.
Ответы
Ответ 1
public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID)
: this(dataSourceID)
{
this._modelState = modelStateDictionary;
}
Это сначала вызовет ваш другой конструктор. Вы также можете использовать base(...
для вызова базового конструктора.
this
в этом случае подразумевается.
Ответ 2
Да, у вас есть несколько вариантов:
1) Обобщите общую логику инициализации в другой метод и вызовите это от каждого конструктора. Вам понадобится этот метод, если вам нужно будет контролировать порядок, в котором элементы инициализируются (например, если _modelState требует инициализации _accountRepository после него):
public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID)
{
this._modelState = modelStateDictionary;
Initialize(dataSourceID);
}
public AccountService(string dataSourceID)
{
Initialize(dataSourceID);
}
private void Initialize(string dataSourceID)
{
this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID);
this._productRepository = StorageHelper.GetTable<Product>(dataSourceID);
}
2) Каскадируйте конструкторы, добавив в конце this
:
public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID) : this(dataSourceID)
{
this._modelState = modelStateDictionary;
}
public AccountService(string dataSourceID)
{
this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID);
this._productRepository = StorageHelper.GetTable<Product>(dataSourceID);
}