[英]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. this
我需要一个概要。 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.
如果有人会这么好心给我一个基本的纲要,我会非常高兴。
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.请注意,使用
: this()
等价于: base()
,不同之处在于它指的是同一类中的构造函数,而不是父类。
There's an article about constructors here (MSDN) , which provides a usage example:这里有一篇关于构造函数的文章(MSDN) ,提供了一个使用示例:
public Employee(int annualSalary)
{
salary = annualSalary;
}
public Employee(int weeklySalary, int numberOfWeeks)
: this(weeklySalary * numberOfWeeks)
{
}
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 http://msdn.microsoft.com/en-us/library/vstudio/ms173115.aspx
The this keyword is used in many context and giving a complete answer will be possible only replicating the entire authoritative source. this 关键字在许多上下文中使用,并且只有复制整个权威来源才能给出完整的答案。 The C# Language Reference
C# 语言参考
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.
this 关键字指的是类的当前实例,也用作扩展方法的第一个参数的修饰符。
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. this
关键字指的是类的当前实例,也用作扩展方法的第一个参数的修饰符。
See this: http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz(v=vs.120).aspx请参阅: http : //msdn.microsoft.com/en-us/library/vstudio/dk1507sz(v=vs.120).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.