zoukankan      html  css  js  c++  java
  • 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="不符合条件";
           }

  • 相关阅读:
    数据库备份与还原
    启明星产品与微软Active Directory活动目录集成说明
    启明星请假系统里,计算工作日的实现
    启明星会议室预定系统Outlook版开始支持Exchange2013与Office365版
    Jquery Mobile实例--利用优酷JSON接口读取视频数据
    高性能且线程安全的两种格式化日期方式
    将数列唯一值化后再求中值的效率比较 第一方案胜出,加索引后在近两百万数据中查出中值耗时0.176秒
    Oracle WITH 语句 语法
    新三种求数列中值SQL之效率再比拼
    rank,dense_rank和row_number函数区别
  • 原文地址:https://www.cnblogs.com/jintuo/p/4217955.html
Copyright © 2011-2022 走看看