CSharp面向对象入门基础Word下载.docx
《CSharp面向对象入门基础Word下载.docx》由会员分享,可在线阅读,更多相关《CSharp面向对象入门基础Word下载.docx(21页珍藏版)》请在冰豆网上搜索。
p2.Age=20;
p2.GiveName("
);
p2.SayHello();
Person3p3=newPerson3();
p3.Age=30;
//Console.WriteLine("
年龄是{0}"
p3.age);
p3.Age=-1;
Console.WriteLine("
p3.Age);
p3.Age1=-100;
p3.Age1);
Person4p4=newPerson4();
p4.Age=30;
p4.Age=p4.Age+1;
Console.WriteLine(p4.Age);
//Person5p5=newPerson5();
//p5.Age=30;
//Console.WriteLine(p5.Age);
Person6p6=newPerson6();
p6.IncAge();
//p6.Age=30;
年龄{0}"
p6.Age);
Person7p7=newPerson7();
p7.Age=30;
Console.WriteLine(p7.Age);
Console.ReadKey();
}
classPerson
publicintHeight;
publicintAge;
privatestringName;
publicvoidSayHello()
大家好,我叫{0},我的身高是{1},我的年龄是{2}"
this.Name,this.Height,this.Age);
classPerson2
publicvoidGiveName(stringname)
if(name=="
jerry"
)
return;
this.Name=name;
睁眼();
this.Name,this.Height,this.Age);
privatevoid睁眼()
睁开双眼"
classPerson3
privateintage;
publicintAge1;
publicintAge
set//赋值
if(value<
0)
this.age=value;
get//取值
returnthis.age;
classPerson4
set
get
return3;
classPerson5
this.Age=value;
//给自己赋值,死循环
returnthis.Age;
classPerson6
publicintAge//只读属性,因为只有get,没有set
get{returnage;
publicvoidIncAge()
age++;
classPerson7
get;
//编译器自动帮我们生成私有字段和set、get代码块。
set;
publicstringName
}
2..聊天机器人
namespace面向对象版聊天机器人
机器人r1=new机器人();
r1.Name="
小I"
r1.Eat(5);
机器人r2=new机器人();
r2.Name="
小J"
r1.Eat(8);
Console.WriteLine();
请选择机器人:
1→小I,2→小J"
机器人r;
stringstr=Console.ReadLine();
if(str=="
1"
r=r1;
//r指向“r1指向的对象”
else
r=r2;
r.SayHello();
while(true)
stringstr1=Console.ReadLine();
r1.Speak(str1);
class机器人
publicstringName{get;
privateintFullLevel{get;
我叫:
{0}"
Name);
publicvoidEat(intfoodCount)
if(FullLevel>
100)
FullLevel=FullLevel+foodCount;
publicvoidSpeak(stringstr)
if(FullLevel<
=0)
饿死了,不说了!
"
if(str.Contains("
姓名"
)||str.Contains("
名字"
))
this.SayHello();
elseif(str.Contains("
女朋友"
年龄小,不考虑!
听不懂!
FullLevel--;
3.构造函数
namespace构造函数1
Personp2=newPerson("
Personp3=newPerson("
20);
Personp4=newPerson();
年龄:
{0},姓名:
{1}"
p1.Age,p1.Name);
p2.Age,p2.Name);
p3.Age,p3.Name);
publicintAge{get;
publicPerson()
Name="
未命名"
Age=0;
publicPerson(stringname)
this.Name=name;
publicPerson(stringname,intage)
this.Age=age;
4.继承
namespace继承
中国人c1=new中国人();
c1.Height=180;
c1.Name="
李小龙"
c1.SayHello();
c1.户口="
北京"
韩国人k1=new韩国人();
k1.Name="
金喜善"
k1.Height=170;
k1.SayHello();
k1.做泡菜();
Personp1=c1;
Personp2=k1;
//中国人zgr=p1;
//报错,因为p1是Person类
中国人zgr=(中国人)p1;
zgr.SayHello();
//中国人zgr1=(中国人)p2;
//一旦程序员的保证不靠谱,照样报错
//zgr1.SayHello();
Objectobj=3;
//Object是所有类的一个基类
classPerson//所有的类都继承于Object类,等价于Person:
Object
publicstringName{get;
set;
publicintAge{get;
publicintHeight{get;
SayHello"
this.Name);
class中国人:
Person