您的位置:首页 > 其它

【面向对象】三重定义——重构、重写、重载

2017-05-14 15:00 225 查看


重构(Refactoring)

【定义】

在原始代码的基础上通过一定的方法,比如添加设计模式,封装类等手段,使软件的性能得到提升,从而提高软件的维护性和拓展性。

【关键代码】

//父类
class Animal
{
......
public string Shout()
{
string result=""
for(int i=0;i<ShoutNum;i++)
result +=getShoutSound()+",";

return "我的名字叫"+name+""+result ;

}

protected virtual string getShoutSound()
{
return "";
}
}

//子类
class Cat:Animal
{
public Cat():base()
{}
public Cat(string name):base(name)
{}
protected override string getShoutSound()
{
return "喵";
}
}
重写(Overriding)

【定义】

子类继承父类的方法时,想做一些修改,这就用到了方法的重写,又称方法覆盖。

【关键代码】

//抽象类animal-----------------------------
class Animal
{
protected string name = "";
public Animal(string name)
{
this.name = name;
}
protected int shouNum = 3;
public int ShoutNum
{
get { return shouNum;}
set { shouNum = value; }

}
public string shout()
{
string result="";
for (int i = 0; i <shouNum; i++)
result += "";
return "我的名字叫" + name + "" + result;
}
//虚拟方法:主要重写的方法
protected virtual string getshoutsound()
{
return "";
}
}
//类cat
class Cat : Animal
{
public Cat(string name)
: base(name)
{ }
//类cat对方法getshoutsound()进行了重写覆盖
public override string getshoutsound()
{
return "喵";
}
}
重载(Overloading)

【定义】

遇到函数或方法有相同的名称,但参数列表不同的情况,可用方法重载

【关键代码】

class Cat
{
private string name="";
public Cat(string name)
{
this.name=name;
}

public Cat()
{
this.name="无名";
}

public string Shout()
{
return "我的名字叫"+name+"喵";
}
}
小结

“一张图胜过千言万语”,在以后的总结中要多加些图帮助理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: