[英]UpCasted field without access
How can I access a field in a UpCasted Object? 如何访问UpCasted对象中的字段? I cannot use Console.WriteLine in order to print
SuperPower
property of a Guy
object 我无法使用Console.WriteLine来打印
Guy
对象的SuperPower
属性
namespace Test
{
class Guy
{
public int Power { get; set; }
}
class BigGuy : Guy
{
public int SuperPower { get; set; }
}
class Program
{
static void Main(string[] args)
{
Guy guy = new Guy();
BigGuy bigGuy = new BigGuy();
bigGuy.SuperPower = 4;
guy = bigGuy;
Console.WriteLine(guy.SuperPower); // Visual studio doesn't accept this line.
}
}
}
When i debug I get an error: 当我调试时出现错误:
'Guy' does not contain a definition for 'SuperPower'
Why can't I access guy.SuperPower
field? 为什么我不能访问
guy.SuperPower
字段?
在访问BigGuy
类的字段之前,您必须将guy
投给BigGuy
:
Console.WriteLine(((BigGuy)guy).SuperPower);
Because the type of the variable is Guy
. 因为变量的类型是
Guy
。 Which means you only have access to properties declared on the Guy
type. 这意味着您只能访问在
Guy
类型上声明的属性。
Imagine if you had a second subclass: 想象一下,如果您还有第二个子类:
class FastGuy : Guy
{
public int SpeedPower { get; set; }
}
guy = bigGuy;
guy = new FastGuy();
The properties you would be able to access would change depending on what value you're assigning. 您将能够访问的属性将根据您分配的值而变化。 That would mean it wouldn't be able to do type checking at compile time.
这意味着它将无法在编译时进行类型检查。
Typically, the point of declaring a type as some less specific type is so that you can act on the object as though it were that type, even though the concrete type may be a subclass. 通常,将类型声明为一些不太具体的类型的目的是,即使具体类型可能是子类,您也可以像对待该类型一样对对象进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.