what is 'this' constructor, what is it for

泪湿孤枕 提交于 2019-12-17 07:54:00

问题


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.


回答1:


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



回答2:


It's used to invoke another constructor in the class:

public class Test {
    public Test() : this("AmazingMrBrock")
    {

    }

    public Test(string name) 
    {
       Console.WriteLine(name);
    }

}

http://msdn.microsoft.com/en-us/library/vstudio/ms173115.aspx




回答3:


The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.

See this: http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz(v=vs.120).aspx




回答4:


The this keyword is used in many context and giving a complete answer will be possible only replicating the entire authoritative source. The C# Language Reference

The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.



来源:https://stackoverflow.com/questions/18729444/what-is-this-constructor-what-is-it-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!