您的位置:首页 > 编程语言 > C#

C#基础知识之类继承

2016-04-21 10:41 609 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassInherit
{
//父类Animal
class Animal
{
//private修饰,它的子类不可以访问
private string _PrivateValue = "private";
//protected修饰,它的子类继承得到
protected int _Weight = 20;
//pubic修饰,它的子类继承得到
public int Weight
{
get
{
return this._Weight;
}
set
{
this._Weight = value;
}
}
//pubic修饰,它的子类继承得到
public void Shout( )
{
System.Console.WriteLine("An animal is shouting...");
}
}
class Dog : Animal
{
//子类专有,父类没有
private string _Name = "旺财";
//子类专有,父类没有
public string Name
{
get
{
return this._Name;
}
set
{
this._Name = value;
}
}
//子类专有,父类没有
public void ShowMe()
{
//子类可以使用从父类继承得到的protected字段:_Name, _Weight
System.Console.WriteLine("A dog, name is {0}, and weight is {1} ...",
this._Name, this._Weight);
}
}

class Program
{
static void Main(string[] args)
{
//创建一个Dog对象
Dog aDog = new Dog( );
//使用Dog从Animal继承得到的属性Weight
System.Console.WriteLine("aDog.Name = {0}, aDog.Weight = {1}", aDog.Name, aDog.Weight);
//使用Dog专有的成员方法ShowMe()
aDog.ShowMe( );
//使用Dog从Animal继承得到的方法Shout()
aDog.Shout( );

//Dog是Animal,所以可以讲Dog对象直接赋值到Animal引用
Animal aml = aDog;
//使用Animal的成员方法
aml.Shout( );
//aml.ShowMe( ); //错误,因为Animal不能直接访问子类的方法。
((Dog) aml).ShowMe( );//正确,先强制转换成Dog在使用,因为aml本身就是一个Dog对象。

Animal bAml = new Animal( );
Dog bDog;
//bDog = (Dog) bAml;  //异常,因为bAml实际上不是Dog对象
bDog = (Dog) aml;   //正确,因为aml本身就是一个Dog对象

System.Console.WriteLine("aml is Animal : {0}", aml is Animal);
System.Console.WriteLine("aml is Dog : {0}", aml is Dog);
System.Console.WriteLine("bAml is Animal : {0}", bAml is Animal);
System.Console.WriteLine("bAml is Dog : {0}", bAml is Dog);
}
}
}


注释的很清楚,这里就不累赘啦,加油!关于C#,C++细节里的那些疑难杂症请访问geeksforgeeks官网(http://www.geeksforgeeks.org/)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  继承 class