构造函数中“this”关键字的function是什么?

我刚刚看到来自MSDN的示例代码并且来自:

namespace IListSourceCS { public class Employee : BusinessObjectBase { private string _id; private string _name; private Decimal parkingId; public Employee() : this(string.Empty, 0) {} // <<--- WHAT IS THIS??? public Employee(string name) : this(name, 0) {} 

它使用该签名调用该类中的其他构造函数。 它是一种根据其他构造函数实现构造函数的方法。 base也可用于调用基类构造函数。 您必须拥有与此匹配的签名构造函数才能使其正常工作。

这允许您使用(string,int)参数调用Employee(当前)类的另一个构造函数。

这是一种初始化称为Constructor Chaining的对象的技术

这个示例可能有助于一些不同的派生……第一个显然有两个构造函数方法在创建实例时…例如

FirstClass oTest1 = new FirstClass(); 或FirstClass oTest1b = new FirstClass(2345);

SECOND类派生自FirstClass。 注意它也有多个构造函数,但是一个是两个参数…双参数签名调用“this()”构造函数(第二个类)…然后调用BASE CLASS( FirstClass)带有整数参数的构造函数…

因此,在创建从其他人派生的类时,可以引用它的OWN类构造函数方法,或者它的基类……类似地在代码中如果你覆盖了一个方法,你可以在BASE()方法中添加一些内容…

是的,比您可能感兴趣的更多,但也许这个澄清也可以帮助其他人……

  public class FirstClass { int SomeValue; public FirstClass() { } public FirstClass( int SomeDefaultValue ) { SomeValue = SomeDefaultValue; } } public class SecondClass : FirstClass { int AnotherValue; string Test; public SecondClass() : base( 123 ) { Test = "testing"; } public SecondClass( int ParmValue1, int ParmValue2 ) : this() { AnotherValue = ParmValue2; } } 

constructor是一个特殊的方法/函数,用于初始化基于类创建的对象。 这是您运行初始化的地方,因为设置默认值,以各种方式初始化成员。

this ”是一个特殊的单词,它指向您所拥有的自己的对象。将其视为对象本身中用于访问内部方法和成员的对象引用。

查看以下链接:

  • C#何时使用“此”关键字
  • 你什么时候使用“this”关键字?