我对 Initialize
方法在构造函数中的典型用途感到有点困惑。
为什么我不能将所有内容都放在构造函数中,为什么下面的示例会调用初始化方法?
private IAzureTable<Product> _productRepository;
public ProductService(string dataSourceID)
{
Initialize(dataSourceID);
}
private void Initialize(string dataSourceID)
{
this._productRepository = StorageHelper.GetTable<Product>(dataSourceID);
}
是否有通常使用的约定?
在此示例中,我是否需要在 Initialize
方法中使用单词 this
?
最佳答案
Why can't I just put everything in the constructor and why does the sample below call the initialize method?
您可以将其全部放在构造函数中。在这个简单的例子中,你应该。构造函数用于初始化您的对象。
有时你会遇到更复杂的事情:
- 有时您会需要一个单独的
Initialize
方法,因为您希望在构造时单独调用它。 - 有时您需要一个,因为您正在编写多个构造函数,并且您希望在它们之间共享一些实现。
- 有时你的初始化很复杂,你想给它的各个部分起个好名字,这样你就知道你的代码在做什么。因此,您将这些部分分解为单独的方法。
这些都不是这段代码的情况,所以我只是跳过它并将代码扔到构造函数中。
Is there a convention that is normally used?
没有。人们会做最容易阅读和理解的事情,需要编写最少额外代码的事情,以及导致最少重复代码的事情。
但是,如果您要公开 Initialize
方法,而不是从构造函数中调用它,我强烈建议您将其命名为 Initialize
。将其设计为仅调用一次。
In this example do I need the word "this." in the Initialize method?
没有。你永远不需要使用 this
来访问类成员,除非你有另一个同名的局部变量。这是一个例子:
public class Something
{
private string someValue;
public class Something(string someValue)
{
// must use "this" to access the member variable,
// because a local variable has the same name
this.someValue = someValue;
}
}
关于c# - Initialize 方法有什么用,我真的需要一个吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8488573/