[英]How can I access the result in Derived 1 and Derived 2 and not the base class
[英]How can I access members of a derived class's base class through the Immediate window in Visual Studio?
使用Visual Studio中的“即时”(或“监视”)窗口(我正在使用VS2015社区版),可以在中断模式下访问类的属性或方法。 但是,对于从另一个类派生的类,如果在派生类中重写了基类的成员,则无法找到一种方法,即使从示例中可以很容易地从代码中进行操作:
public class Program
{
static void Main(string[] args)
{
var ostrich = new Ostrich();
ostrich.WriteType();
Console.ReadKey();
}
}
public class Animal
{
public void WriteType()
{
Console.WriteLine("I'm an {0}", this.Name);
}
public virtual string Name => "animal";
}
public class Ostrich : Animal
{
public override string Name => $"ostrich, not an {base.Name}";
}
如果运行此代码,则输出(显然)是:
我是鸵鸟,不是动物
如果我在Ostrich
类的Name
属性内设置断点,然后在Instant窗口中检查Name
属性,则输出如下所示:
?this.Name
"ostrich, not an animal"
相反,如果我要求运行基类的实现,那么我期望输出为“动物”。 实际上,我得到以下信息:
?base.Name
"ostrich, not an animal"
这似乎不仅无济于事,而且实际上是误导/不正确的:我宁愿返回错误而不是错误的答案。
使用监视窗口,仅显示派生类的实现:
有什么方法可以使用即时窗口访问类的基类的重写成员?
我认为很base.
在课外不公开提供。 如果要在类实现之外编写代码,则要访问Animal
而不是Ostrich
的属性,则可以将其括弧式转换为Animal
。
((Animal)obj).Name
问题在于,即使这仍然会给您带来ostrich
而不是animal
,因为这恰恰是应该实现的行为,即您可以访问您认为属于Animal
类型的对象的Name
属性,但是其功能可以在派生类中重写。
从编译器的角度来看,我不确定它的来龙去脉,但是如果基本实现的代码甚至没有出现在已编译的Ostrich
,也不会感到惊讶,除非Ostrich
可以访问的代码base.
我同意即时窗口允许您使用base.
的事实base.
然后给您一个错误的答案,这很容易引起混淆,并且很可能是Visual Studio中的错误,除非其他人可以解释这是怎么回事。
如果您在Ostrich
包含一些访问base.Name
代码, base.Name
窗口的行为将很有趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.