从父上下文引用`this`子项

时间:2013-11-21 22:00:40

标签: c# inheritance reference

我有一个Parent班,孩子很少。我希望每个孩子都把它的结构写成共享日志。我的日志有一个实际使用调用对象类型的方法log_my_creation(object)。如果我从log_my_creation(this)构造函数中调用Parent,我显然会得到Parent的类型而不是特定的子项,同时我会从每个子项的构造函数中单独调用log_my_creation(this) ,这感觉有点不对劲。

我的问题是:虽然在父方法中,我怎么能把它称为孩子呢。

澄清代码:

现在:

class Parent{}

class Child_1
{
 public Child1()
 {
  log.log_my_creation(this);
 }
}

一厢情愿(以下代码当然不会到期):

class Parent
{
 public Parent()
 {
  log.log_my_creation(this); // logs the creation of the child it is 
 }
}

这样的代码如下:

Parent p = new Parent();
Child1 c1 = new Child1();
Child1 c2 = new Child2();

- 输出(记录)以下内容:

A Parent was constructed.
A Child1 was constructed.
A Child2 was constructed.

1 个答案:

答案 0 :(得分:4)

  

如果我从Parent构造函数中调用log_my_creation(this),我显然会得到Parent的类型而不是特定的子类

不,你不会。

您要求的行为是代码已经表现的方式。 this是指实际对象的实例,在这种情况下,它的运行时类型将是子类型,而不是父类型,因为实例实际上是子类的实例。

父构造函数中this的编译时类型将为Parent,但this的运行时类型将是实际创建的子类型。如果您的日志方法针对不同类型具有不同的重载,而不是使用反射来确定要记录的对象的类型,那么这将是您的问题。更改记录器以查看运行时类型,而不是编译时类型(或提供具有该行为的其他方法)。

相关问题