【发布时间】:2016-10-03 14:25:50
【问题描述】:
我有以下代码
public class Base {
public Base() {}
public virtual void IdentifyYourself() {
Debug.Log("I am a base");
}
public void Identify() { this.IdentifyYourself(); }
}
public class Derived : Base {
public Derived() {}
public override void IdentifyYourself() {
Debug.Log("I am a derived");
}
}
我在不同的入口点运行以下测试代码:
Base investigateThis = new Derived();
investigateThis.Identify()
输出是:“我是派生的”
所以无论在哪里使用 C# 'this' 关键字;无论在什么范围内使用“this”,它是否总是引用运行时类型?
奖励点给那些比我更能“谷歌”并找到 MSDN 文档关于“这种”(双关语)行为的人。
最后,有没有人碰巧知道幕后发生了什么?只是演员表吗?
更新 #1:修正了代码中的拼写错误;根据当前的答案集,我想我没有完全理解 MSDN 文档中“..is the current instance..”的含义。
更新#2:抱歉,我不确定我是否应该提出一个单独的问题,但在进一步调查中,我再次感到困惑;鉴于此更新的代码,为什么输出都是:“我是派生的”和“这是一个基础!”。
其他人没有回答“this”确实是运行时类型吗?如果我更新的问题仍然不清楚,请告诉我。
更新代码:
public class Base {
public Base() {}
public virtual void IdentifyYourself() {
Debug.Log("I am a base");
}
//Updated the code here...
public void Identify() { this.IdentifyYourself(); AnotherTake(); }
public void AnotherTake() { WhatIsItExactly(this); }
public void WhatIsItExactly(Derived thing) {
Debug.Log("It is a derived!");
}
public void WhatIsItExactly(Base thing) {
Debug.Log("It is a base!");
}
}
public class Derived : Base {
public Derived() {}
public override void IdentifyYourself() {
Debug.Log("I am a derived");
}
}
【问题讨论】:
-
这是合乎逻辑的事情:
this可以指代什么而不是当前对象?不是that,是this。你的问题甚至不是关于this,而是关于虚拟方法。 -
google
c# this这(双关语)是第一个结果msdn.microsoft.com/en-us/library/dk1507sz.aspx -
你的派生类目前不派生自对象以外的任何东西。
-
@Nkosi yep "this 关键字指的是类的当前实例..."
-
我会问更新 #2 作为一个单独的问题,因为它现在是关于运行时绑定与多态性的。
标签: c# inheritance this virtual-functions