2011-12-11 24 views
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); 
    } 

有一些办法,我可以简化构造所以每个不必做StorageHelper电话?

我也需要指定这个。 ?

回答

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

} 

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

this在这种情况下是隐含的。

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); 
} 

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); 
} 
+0

只是为了确认。我可以删除哪些“这个”这个词? –

+0

不完全清楚你要问什么,但如果你询问'this._'代码,你可以删除所有这些代码。例如,'this._accountRepository'也可以写成'_accountRepository'。我所指的'this'与构造函数声明位于同一行(滚动到右边看它)。 –

+1

@RichardM:几乎所有的人。除非你传入一个具有相同名字的变量,否则''this.'几乎总是可以在上下文中被推断出来。有些人喜欢它,引用可读性(更明确)。其他人也出于同样的原因不喜欢它(冗余信息)。 –