什么是“这个"构造函数,它是做什么用的 [英] what is 'this' constructor, what is it for

查看:23
本文介绍了什么是“这个"构造函数,它是做什么用的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习过程中,我有一个问题无法找到满意的答案.

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

this 我需要一个概要.我一直看到它,人们已经为我使用它的代码提出了修复建议.我真的不知道它到底是做什么的.如果有人能这么好心地给我一个基本的纲要,我会非常高兴.

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.

推荐答案

用于引用同一个类中的另一个构造函数.你用它来继承"另一个构造函数:

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

在上面,当调用第二个构造函数时,它先执行无参数构造函数,然后再执行自己.请注意,使用 :this() 等价于 :base(),不同之处在于它指的是同一类中的构造函数,而不是父类.

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.

有一篇关于构造函数的文章这里 (MSDN),它提供了一个使用示例:

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

这篇关于什么是“这个"构造函数,它是做什么用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆