Welcome to OStack Knowledge Sharing 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# - what is 'this' constructor, what is it for

I'm in the learning process and I have a question I havent been able to find a satisfactory answer for.

this I need a rundown on it. I keep seeing it and people have suggested fixes for my code that use it. I really have no idea what exactly it does. If someone would be so kind as to give me a basic rundown on it I would be really happy.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It's used to refer to another constructor in the same class. You use it to "inherit" another constructor:

public MyClass() {}

public MyClass(string something) : this() {}

In the above, when the second constructor is invoked, it executes the parameterless constructor first, before executing itself. Note that using : this() is the equivalent of : base(), except it refers to a constructor in the same class, instead of the parent class.

There's an article about constructors here (MSDN), which provides a usage example:

public Employee(int annualSalary)
{
    salary = annualSalary;
}

public Employee(int weeklySalary, int numberOfWeeks)
    : this(weeklySalary * numberOfWeeks)
{
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...