有一个疑惑如下:
using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class Program
{
public abstract class animal
{
public abstract void Eat();
} public class bird : animal
{
private string type;
public bird()
{
Type="bird";
}
public string Type
{
get
{
return type;
}
set
{
type = value;
}
}
public override void Eat()
{
Console.WriteLine("Bira is eating!");
}
}
public class chichen : bird
{
private string type; public string Type
{
get
{
return type;
}
set
{
type = value;
}
} public chichen()
{
Type = "chichen";
}
public override void Eat()
{
Console.WriteLine("Chichen is eating!");
}
} static void Main(string[] args)
{
bird app = new chichen();
Console.WriteLine("aap's Type is {0}.",app.Type);
app.Eat();
Console.ReadKey();
}
}
}
上述代码输入app.Type输出是bird;
但是把红色代码去掉后app.Type输出是chichen,请大侠们帮忙解释下。
using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class Program
{
public abstract class animal
{
public abstract void Eat();
} public class bird : animal
{
private string type;
public bird()
{
Type="bird";
}
public string Type
{
get
{
return type;
}
set
{
type = value;
}
}
public override void Eat()
{
Console.WriteLine("Bira is eating!");
}
}
public class chichen : bird
{
private string type; public string Type
{
get
{
return type;
}
set
{
type = value;
}
} public chichen()
{
Type = "chichen";
}
public override void Eat()
{
Console.WriteLine("Chichen is eating!");
}
} static void Main(string[] args)
{
bird app = new chichen();
Console.WriteLine("aap's Type is {0}.",app.Type);
app.Eat();
Console.ReadKey();
}
}
}
上述代码输入app.Type输出是bird;
但是把红色代码去掉后app.Type输出是chichen,请大侠们帮忙解释下。
解决方案 »
- 【菜鸟求助:程序出错】用接口实现:统计每月图书销售情况,并将每月销售100本的图书信息显示出来。
- *.ToString() 和 (string)* 那个快?
- winform 实现网页抓取功能!求思路,有源码更好!!分不够另开贴
- 如何在panel上获取到动态生成的控件?求救各位,在线等!
- ShowDialog问题
- 在WINFORM中能不能触发一个页面的SUBMIT,谢谢
- 还是关于.net中采用c#语言如何防止点击浏览器的后退按钮进入不该进入的页面
- 求解:如何利用webclient下载
- 请问哪位大虾知道后缀名为.rmp的文件如何下载下来?急,在线等待,马上给分
- 简单问题
- 怎样获取视频的每一帧图像?
- session用户的问题
他说先执行基类的构造函数,再执行派生类的构造函数
所以会有这样的结果如果你加上了红色的区域之后
那么Type就默认为派生类中的属性字段了
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.20090116b.cs(51,27): warning CS0108: 'test.chichen.Type' hides inherited member
'test.bird.Type'. Use the new keyword if hiding was intended.
20090116b.cs(27,27): (Location of symbol related to previous warning)
E:\C#\Demo>20090116b
aap's Type is bird.
Chichen is eating!
请按任意键继续. . .红色部分说的是子类中的字段属性与父类中的重名了你把chichen类中的Type属性改成Type1试试...
你的children 隱掉了父類的Type,但你在創建子類對象時,又把它轉換成父類對象,輸出的當然是父類如果子類時重寫父類的,那么在轉換為父類時,會先找子類有沒有重寫Type,有就輸出子類,沒有就輸出父類你目前的這種做法,其實就是用new 与 override 的區別