如何访问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字段?
发布于 2017-07-22 19:43:37
在访问BigGuy类的字段之前,必须将guy转换为BigGuy:
Console.WriteLine(((BigGuy)guy).SuperPower);发布于 2017-07-22 19:45:28
因为变量的类型是Guy。这意味着您只能访问在Guy类型上声明的属性。
想象一下,如果你有第二个子类:
class FastGuy : Guy
{
public int SpeedPower { get; set; }
}
guy = bigGuy;
guy = new FastGuy();您能够访问的属性将根据您所赋值的不同而变化。这意味着它不能在编译时进行类型检查。
通常,将一个类型声明为某个不太具体的类型的意义在于,即使具体类型可能是一个子类,您也可以对该对象执行操作,就好像它就是该类型一样。
https://stackoverflow.com/questions/45254117
复制相似问题