在对象初始值设定项中使用“this”

GET*_*Tah 2 c# initialization

我有以下问题:

public class ChildClass{
   public Object Parent = null;
}
public class ParentClass{
   public ChildClass CreateChild(){
        return new ChildClass{ Parent = this; }
   }
}
Run Code Online (Sandbox Code Playgroud)

我在理解对象初始值设定项时遇到了一些困难。方法中CreateChild(), 是thisParentClassChildClass

Ode*_*ded 5

this将引用它所在的类。

在示例中,this将是 的实例ParentClass,因为它是的主体内声明的ParentClass

  • 对象初始值设定项不在“ChildClass”内,而是在“ParentClass”内。因此 `this` 指的是 `ParentClass` 的当前实例。对象初始值设定项不属于“ChildClass”,而是属于“ParentClass”的“CreateChild”方法的代码。“public class ParentClass{” 和最后的“}” 之间的所有内容都属于 `ParentClass`。 (2认同)