2015-01-12 面向对象的程序设计

一,定义:面向对象中,类为最小的单位,通过类来进行交互

 

例:

首先新添加一个类student,在这个新建的类中,写入规则

namespace mianxiangduixiang
{
class student
 {
  //类里可以定义成员变量,道理等同于结构体
   public int code; //定义的变量一般叫做类的属性
   public string name; //public是修饰符,代表访问范围
   private string sex; //private表示只能访问student中的

   public int jiafa(int a)

   {

    return a+10;

   }
 }
}

然后在program中引用

class Program
{
    static void Main(string[] args)
    {
        student s = new student(); //创建一个student类的对象s,通过new初始化
        s.code = 101; //为对象的属性进行赋值
        s.name = "张三";

        int a=s.jiafa(5);  //通过对象调用方法

        student s2 = new student();
        s2.name = "李四";
        Console.WriteLine(s2.name); //取值打印

    }
}

 

//根据对象的年龄进行判断是否成年

1.首先在student.cs中:

public bool panduan(student sdata)
{
if (sdata.nianling >=18)
{
return true;
}
else
{
return false;
}

2.然后在program中:

student s3 = new student();   //定义了一个S3

s3.nianling = 17;                 

bool b = s3.panduan(s3);  //把s3传到 sdata,让sdata=s3
Console.WriteLine(b);

 

//写一个函数,输入参数是一个int数组,降序排序然后返回
public int[] Paixu(int[] shuzu)
{
    int count = shuzu.Length;
    for (int m = 0; m < count- 1; m++)
    {
        for (int n = m; n < count; n++)
       {
            if (shuzu[m] < shuzu[n])
           {
                int zhong;
                zhong = shuzu[m];
                shuzu[m] = shuzu[n];
                shuzu[n] = zhong;

           }
       }
}
return shuzu;
}

 

static void Main(string[] args)
{

int[] shuzu = new int[10];
for (int m = 0; m < 10; m++)
{
      shuzu[m] = int.Parse(Console.ReadLine());
}
Console.WriteLine("排序后为:");

student s = new student();
shuzu = s.Paixu(shuzu);

foreach (int x in shuzu)
{
    Console.WriteLine(x);
}
Console.ReadLine();
}

 

二、封装:

通过鼠标操作的方法:右键→重构→封装字段

public int code
{
  get {return code;}  //读访问器
  set {code=value;}  //写访问器
}
private string name;
private string sex;

public string nianling
{
  get {return nianling;}   //读访问器
  set {                          //可以在set中添加条件

        if(value.Length<=10)
         {nianling=value;}
       else
      {
         nianling="不符合条件";
       }

posted @ 2015-01-12 16:39  雪山飞驴  阅读(122)  评论(0编辑  收藏  举报