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

C#基础------面向对象

2015-08-25 21:57 405 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OOP
{
class Program
{
static void Main(string[] args)
{
//面向对象
//三大特性:封装,继承,多态
//类(Class)对象(Object):人,王力宏

//创建Person类的对象

//new 才会产生新的对象,对象是引用传递,改变地址
Person wlh = new Person();
wlh.SetName("王力宏");
wlh.SetAge(30);
wlh.Say();

Person yzk = wlh;//yzk指向wlh当前所指向的对象
yzk.SetName("杨中科");
yzk.SetAge(18);
yzk.Say();//杨中科
wlh.Say();//杨中科

//wlh指向新创建的对象
wlh = new Person();
wlh.SetName("林志炫");
wlh.Say();//林志炫

Person p = new Person();
p.SetAge(30);
Test(p);
p.Say();//35

Person p1 = null;//声明变量,不指向任何对象
p1.Say()//表示p1指向这个对象的Say()方法,由于p1没有指向任何对象,所以会报异常
}

//把一个对象传递去方法中,传递的也是同一份引用
static void Test(Person p)
{
//这个p就是Person p = new Person();这个对象
p.SetAge(p.GetAge()+5);
}
}
//Person类
class Person
{
//字段用来描述类内部的信息(不同类的对象所不同的)
private string _name;
private int _age;
//方法是类的“行为”,接受外界设定的“名字”
public void SetName(string name)
{
this._name = name;
}
//获取name值
public string GetName()
{
return this._name;
}
//接受外界设定的“年龄”
public void SetAge(int age)
{
this._age = age;
}
//获取age值
public int GetAge()
{
return this._age;
}
//执行说话动作
public void Say()
{
Console.WriteLine("我叫{0},我{1}岁了!",this._name,this._age);
Console.ReadKey();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: