Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c# - base() and this() constructors best practices

Under what conditions am I supposed to make the :base() and :this() constructor calls following my constructor's parentheses (or even in other places in the code). When are these calls good practices and when are they mandatory?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

: base(...)

If you omit the call to a base constructor it will call the default base constructor automatically.

It is mandatory to call a base constructor explicitly if there is no default constructor.

Even if there is a default constructor you may still wish to call a different constructor than the default constructor. In this case you may still wish to use base(foo, bar) to call a different constructor than the base constructor.

I do not consider it to be a bad practice to omit base() when you want to call to the base class default constructor, although if you like to be explicit I see no harm in including it. It is a matter of taste.

: this(...)

This syntax allows you to call one constructor with a different signature from another within the same class. It is never mandatory to do this, but can sometimes be useful.

An example of when it can be useful is for reusing common code in the constructors. For example in C# 3.5 or before you may want to simulate optional parameters on a constructor:

Foo(int x, int y)
{
     this.x = x;
     this.y = y;
}

Foo(int x) : this(x, 10) {}  // y defaults to 10

With C# 4.0 optional parameters are now available which reduces the need for this approach.

An alternative way to reuse code in constructors is to factor it out into a static function which is called from each constructor that wishes to use it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...