无访问权限的上转换字段



如何访问UpCasted对象中的字段?我无法使用 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.
}
}
}

调试时出现错误:

'Guy' does not contain a definition for 'SuperPower' 

为什么我无法访问guy.SuperPower字段?

在访问类BigGuy字段之前,您必须将guy转换为BigGuy

Console.WriteLine(((BigGuy)guy).SuperPower);

因为变量的类型是Guy.这意味着您只能访问在Guy类型上声明的属性。

想象一下,如果你有第二个子类:

class FastGuy : Guy
{
public int SpeedPower { get; set; }
}
guy = bigGuy;
guy = new FastGuy();

您可以访问的属性将根据您分配的值而更改。这意味着它将无法在编译时进行类型检查。

通常,将类型声明为一些不太具体的类型的目的是,即使具体类型可能是子类,也可以像该类型一样对对象进行操作。

最新更新