首页 / Unity3d / C#

读一读

class Human{
    public virtual void CleanRoom(){
        Console.WriteLine("Human");
    }
}
class Man:Human{
    public override void CleanRoom(){
        Console.WriteLine("Man");
    }
}
class Woman:Human{
    public override void CleanRoom(){
        Console.WriteLine("Woman");
    }
}

Human a = new Man();
Human b = new Woman();
a.CleanRoom();   b.CleanRoom();

自动调用相应的方法

同一个方法,但是里面的操作不一样


class Complex{
    public int Number{get;set;}
    public static Complex operator +(Complex a,Complex b){
        Complex c = new Complex();
        c.Number = a.Number+b.Number;
        return c;
    }
}

重载+,可以使用类与类直接相加


public static void PrintHello(){
    Console.WriteLine("Hello");
}
public static void PrintHello(string s){
    Console.WriteLine("hello{0}",s);
}

通过参数的数量和类型的不同来实现同名的方法,执行不同的功能。


class Animal{
    public intAge{get;set;}
    public virtual void Bite(){}
}
class Dog:Animal{
    public override void Bite(){
        Console.WriteLine(Age);        
    }
}

父类方法声明为virtual,说明在子类中可以override重写此方法,若没有声明virtual,可以在方法中+new隐藏父方法

继承中实例化先调用父类构造函数再去调用子类的构造函数

当父类构造函数含有多个时,一般只调用默认的构造函数,可以在子类构造函数中指定父类构造函数:base()。也可以引用自身的:this()


Animal dog=new Dog();

用父类来引用子类的实例,调用重写方法是为子类的方法,因为它已经覆盖了父类的方法。当调用的是为new的隐藏父类方法时,因为引用为父类,所以调用的是父类方法,可以通过强制转化为Dog来调用子类的new隐藏了的父类方法。


public,private,internal,protected

public 允许外部访问

private 只能在类的本身访问

internal 在这个类所在的程序集中都能方访问

程序集是一个包,一个项目,可以是.exe或.dll,一个程序集可以包含多个namespace

protected 类本身与派生类可访问


SortList<int,int> sl=new SortList<int,int>();
sl.Add(5,100);
sl.Add(1,102);
foreach(var sle in sl){
    Console.WriteLine(sle.value);
}

Dictionary<string,string> d=new Dictionary<string,string>();
d.Add("first","chicai");

<string,string>对应的是键值的类型

强类型,线程不安全


Hashtable ht = new Hashtable();
ht.Add("First","chi");
ht.Add("Second","cai");

弱类型的键值对


List<int> intList = new List<int>();
//List的常用方法,强类型
intList.Add(600);
intList.AddRange(new int[]{501,502});//添加多个元素
intList.Contains(200);//判断是否存在元素
intList.Indexof(501);
intList.Remove(501);
intList.RemoveAt(index);
intList.Insert(1,1001);//指定位置插入
intList.Capacity;//集合的总大小
intList.Count;//元素的大小

集合一般在 System.Collection命名空间下

因为数组长度一般是固定的,所以要使用集合

ArrayList al = new ArrayList();
al.Add(5);
al.Add("hello");
al.Remove(5);

每个元素都被当成object。类型不安全。