我可以在C#中组合构造函数吗?

Sam*_*tar 11 c#

我有以下代码:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

有什么方法可以简化构造函数,以便每个人都不必执行StorageHelper调用吗?

我还需要指定这个.?

Yur*_*ich 22

public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID)
    : this(dataSourceID)
{
    this._modelState = modelStateDictionary;

}
Run Code Online (Sandbox Code Playgroud)

这将首先调用您的其他构造函数.您还可以使用base(...调用基础构造函数.

this 在这种情况下暗示.


com*_*ech 6

是的,你有几个选择:

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);
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)