c#基础学习3---总结

来源:互联网 发布:网络名词流行用语2016 编辑:程序博客网 时间:2024/06/06 03:59
1.面向对象:封装,继承,多态
  成员访问级别解决的就是:封装。设定那些只读,只写,读写
  public 公共的    private 私用的(类内部访问)  internal,protected
  字段永远要private 字段开头都是按小写开头
 
2.定义类,字段
  class Person
  {
    public string name;
    public int height;
  }

 Person p1=new Person();
 p1.name="aaa";
 p1.height=22;

 Person p2=p1;// 让p2指向p1当前指定的对象,等于p2,p1指向同一个对象。
 Person p3=new Person();  p3=null;切掉指向
 交换两个引用类型时Swap(string a,string b)交换不了


3.属性(如果字段时public 无法拒绝非法值)
 class Person
  {
    private string job;
    public string job//属性不存值,而是由相应字段存
    {
        get{ return job;}
        set{ this.job=value;}
    }//编译器帮你生成两个方法get_属性名,set_属性名
   public int Age  //编译器自动帮我们生成 private int <Age>_...,还有两个方法
   {
    get;
    set;
   }
  }

4.构造函数(没有返回值的函数)
 class Person
{
  public Person()//方法名与类名相同
  {
  }
}不写的时候,默认有一个无参的构造函数


5.继承
  class Person
  {
    private string name;
    public string Name{
      get;set;
   }
   
   private int age;
   public int Age
   {
     get;
     set;
   }
  }


  class Chinese:Person//继承
  {
    public void HuKu()
    {
      Console.WriteLine("中国人有户口");
    }
  }

  class Japenese:Person
  {
    public void PuFu()
    {
      Console.WriteLine("什么颜色的都有");
    }
  }



  static void Main(string[] args)
  {
    Person p=new Person();
    Chinese c=new Chinese();
    p=c;//父类可以指向子类 人---(标签)--》中国人。
    Person p1=new Person();
    Chinese c1=(Chinese)p1;//要显示转换才行,如果p1不是Chinese则为报错,最好采用p1 as Chinese,如果不是,则返回 null。C1只能调用自己的方法
    if(p1 is Chinese)//判断类型。
  }
构造函数:父类先构造,后子类

6.异常错误
  try
  {
     代码1  //如果try发生异常
     代码2 不会执行(try括号中的代码)
  }
  catch
  {
    //如果try发生异常,则这里会执行
  }
  ....后面代码也会执行

  try
  {

  }
  catch
  {
  }
  finally
  {
    //不管怎么样,这里都会执行
  }
7.常量 const
8.static 静态变量(全局变量),不需要对象
 class A
 {
    public static int F1;
    public int Age;
    public void Hello()//非静态函数可以调用静态变量,因为静态变量是没  有对象的。按照原则分析就OK。
    {

    }
 }
  对于A类只有一份,不与对象有关。

9.sealed 密闭类,不能被继承,String 类是密闭类,不能继承String类的
10.命名空间 namespace
 using 引用命名空间,声明时,如果不是在同一个命名空间下面则需要引用,或者用命名空间+类名来实例化对象。
11.索引器(如何来实现索引器:通过public string this[int index ],get ,set 方法来实现,索引器原理)
  class Myarr
  {
    private string chind1="小毛";
    private string chind2="二毛";
    private string chind3="三毛";

    public string this[int index]
    {
       get {
         if(index==0)
          {
             return chind1;
          }
         if(index==1)
          {
            return chind2;
          }
          if(index==2)
          {
             return chind3;
          }
          throw new Exception("没有对应的值");
       }
       set{
         
          throw new Exception("没有对应值");
         }
       set
        {
         if(index==0)
          {
           chind1=value;
          }
         else if(index==1)
         {
           chind2=value;
         }else if(index==2)
         {
           chind3=value;
         }
         else
         {
          throw new Exception("怎么设置的呢");
         }
        }
    }

  }


原创粉丝点击