索引 操作符 指针

一:数组索引器
    如果用foreach的话,需要从IEnumerable继承
    public class PeopleCollection : IEnumerable
    而且需要重载
    IEnumerator IEnumerable.GetEnumerator()
    { return arPeople.GetEnumerator(); }

    public class Person
    {
        public int Age;
        public string FirstName, LastName;

        public Person() { }
        public Person(string firstName, string lastName, int age)
        {
            Age = age;
            FirstName = firstName;
            LastName = lastName;
        }
        public override string ToString()
        {
            return string.Format("Name: {0} {1}, Age: {2}", FirstName, LastName, Age);
        }
    }

    public class PeopleCollection// : IEnumerable(使用FOREACH时会用到)
    {
        private ArrayList arPeople = new ArrayList();

        public PeopleCollection() { }

        public Person this[int index]
        {
            get { return (Person)arPeople[index]; }
            set { arPeople.Insert(index, value); }
        }

        public Person GetPerson(int pos)
        { return (Person)arPeople[pos]; }

        public void AddPerson(Person p)
        { arPeople.Add(p); }

        public void ClearPeople()
        { arPeople.Clear(); }

        public int Count
        { get { return arPeople.Count; } }

        //IEnumerator IEnumerable.GetEnumerator()(使用FOREACH时会用到)
        //{ return arPeople.GetEnumerator(); }
    }

    static void Main(string[] args)
    {
        Console.WriteLine("***** Fun with Indexers *****/n");

        PeopleCollection myPeople = new PeopleCollection();

        myPeople[0] = new Person("Homer", "Simpson", 40);
        myPeople[1] = new Person("Marge", "Simpson", 38);
        myPeople[2] = new Person("Lisa", "Simpson", 9);
        myPeople[3] = new Person("Bart", "Simpson", 7);
        myPeople[4] = new Person("Maggie", "Simpson", 2);

        //foreach(Person p in myPeople)如果用FOREACH的话,需要加IEnumerable
        //{           
        //    Console.WriteLine("Name: {0} {1}", p.FirstName, p.LastName);
        //    Console.WriteLine("Age: {0}", p.Age);
        //    Console.WriteLine();
        //}

        //等价于
        //IEnumerator enum1 = myPeople.GetEnumerator();
        //do
        //{
        //    string enum2 = (string)enum1.get_Current(); // 冗余转换
        //    Console.WriteLine(item);
        //} while(enum1.MoveNext());
        //((IDisposable)enum1).Dispose();

        for (int i = 0; i < myPeople.Count; i++)
        {
            Console.WriteLine("Person number: {0}", i);
            Console.WriteLine("Name: {0} {1}", myPeople[i].FirstName, myPeople[i].LastName);
            Console.WriteLine("Age: {0}", myPeople[i].Age);
            Console.WriteLine();
        }

        Console.ReadLine();
    }

二:Sting 中的索引,
    如果是String作为索引标识的话,则需要用Dictionary而非ArrayList。
    public class PeopleCollection : IEnumerable
    {
        private Dictionary<string, Person> listPeople = new Dictionary<string, Person>();

        public Person this[string name]
        {
            get { return listPeople[name]; }
            set { listPeople[name] = value; }
        }

        public PeopleCollection() { }

        public void ClearPeople()
        { listPeople.Clear(); }

        public int Count
        { get { return listPeople.Count; } }

        IEnumerator IEnumerable.GetEnumerator()
        { return listPeople.GetEnumerator(); }
    }

    static void Main(string[] args)
    {
        PeopleCollection myPeople = new PeopleCollection();

        myPeople["Homer"] = new Person("Homer", "Simpson", 40);
        myPeople["Marge"] = new Person("Marge", "Simpson", 38);

        Person p = myPeople["Homer"];
        Console.WriteLine(p);

        p = myPeople["Marge"];
        Console.WriteLine(p);

        Console.ReadLine();
    }

三:多维函数的处理
    public class SomeContainer
    {
        private int[,] my2DintArray = new int[10, 10];
        public int this[int row, int column]
        {
            get { return my2DintArray[row, column]; }
            set { my2DintArray[row, column] = value; }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            SomeContainer sc = new SomeContainer();
            sc[2, 3] = 5;
            Console.WriteLine(sc[2, 3].ToString());
        }
    }

四:操作符重载,以Point为例
    public struct Point : IComparable
    {
        private int x, y;
        public Point(int xPos, int yPos)
        {
            x = xPos; y = yPos;
        }

        public override string ToString()
        {
            return string.Format("[{0}, {1}]", this.x, this.y);
        }

        public override bool Equals(object o)
        {
            return o.ToString() == this.ToString();
        }

        public override int GetHashCode()
        {
            return this.ToString().GetHashCode();
        }

        public static Point operator +(Point p1, Point p2)
        {
            return new Point(p1.x + p2.x, p1.y + p2.y);
        }

        public static Point operator +(Point p1, int change)
        {
            return new Point(p1.x + change, p1.y + change);
        }
        public static Point operator +(int change, Point p1)
        {
            return new Point(p1.x + change, p1.y + change);
        }

        public static Point operator -(Point p1, Point p2)
        {
            return new Point(p1.x - p2.x, p1.y - p2.y);
        }

        public static Point operator ++(Point p1)
        {
            return new Point(p1.x + 1, p1.y + 1);
        }

        public static Point operator --(Point p1)
        {
            return new Point(p1.x - 1, p1.y - 1);
        }

        public static bool operator <(Point p1, Point p2)
        {
            return (p1.CompareTo(p2) < 0);
        }

        public static bool operator >(Point p1, Point p2)
        {
            return (p1.CompareTo(p2) > 0);
        }

        public static bool operator <=(Point p1, Point p2)
        {
            return (p1.CompareTo(p2) <= 0);
        }

        public static bool operator >=(Point p1, Point p2)
        {
            return (p1.CompareTo(p2) >= 0);
        }

        public static bool operator ==(Point p1, Point p2)
        {
            return p1.Equals(p2);
        }

        public static bool operator !=(Point p1, Point p2)
        {
            return !p1.Equals(p2);
        }

        public int CompareTo(object obj)
        {
            if (obj is Point)
            {
                Point p = (Point)obj;
                if (this.x > p.x && this.y > p.y)
                    return 1;
                if (this.x < p.x && this.y < p.y)
                    return -1;
                else
                    return 0;
            }
            else
                throw new ArgumentException();
        }
    }
    static void Main(string[] args)
    {
        Point ptOne = new Point(100, 100);
        Point ptTwo = new Point(40, 40);
        Console.WriteLine("ptOne = {0}", ptOne);
        Console.WriteLine("ptTwo = {0}", ptTwo);

        Console.WriteLine("ptOne + ptTwo: {0} ", ptOne + ptTwo);
        Console.WriteLine("ptOne - ptTwo: {0} ", ptOne - ptTwo);

        Point biggerPoint = ptOne + 10;
        Console.WriteLine("ptOne + 10 = {0}", biggerPoint);
        Console.WriteLine("10 + biggerPoint = {0}", 10 + biggerPoint);

        Point ptThree = new Point(90, 5);
        Console.WriteLine("ptThree = {0}", ptThree);
        Console.WriteLine("ptThree += ptTwo: {0}", ptThree += ptTwo);

        Point ptFour = new Point(0, 500);
        Console.WriteLine("ptFour = {0}", ptFour);
        Console.WriteLine("ptFour -= ptThree: {0}", ptFour -= ptThree);

        Point ptFive = new Point(1, 1);
        Console.WriteLine("++ptFive = {0}", ++ptFive);  // [2, 2]
        Console.WriteLine("--ptFive = {0}", --ptFive);  // [1, 1]

        Point ptSix = new Point(20, 20);
        Console.WriteLine("ptSix++ = {0}", ptSix++);  // [20, 20]
        Console.WriteLine("ptSix-- = {0}", ptSix--);  // [21, 21]

        Console.WriteLine("ptOne == ptTwo : {0}", ptOne == ptTwo);
        Console.WriteLine("ptOne != ptTwo : {0}", ptOne != ptTwo);

        Console.WriteLine("ptOne < ptTwo : {0}", ptOne < ptTwo);
        Console.WriteLine("ptOne > ptTwo : {0}", ptOne > ptTwo);
    }

五:转换,隐式转换和显示转换
    public struct Rectangle
    {
        public int Width, Height;
        public Rectangle(int w, int h)
        {
            Width = w; Height = h;
        }
        public override string ToString()
        {
            return string.Format("[Width = {0}; Height = {1}]", Width, Height);
        }
        //将Square转换成Rectangle
        public static implicit operator Rectangle(Square s)
        {
            Rectangle r;
            r.Height = s.Length;
            r.Width = s.Length * 2;
            return r;
        }
    }
    public struct Square
    {
        public int Length;
        public Square(int l)
        {
            Length = l;
        }
        public override string ToString()
        {
            return string.Format("[Length = {0}]", Length);
        }
        //将Rectangle转换成Square
        public static explicit operator Square(Rectangle r)
        {
            Square s;
            s.Length = r.Height;
            return s;
        }
        //将int转换成Square
        public static implicit operator Square(int sideLength)
        {
            Square newSq;
            newSq.Length = sideLength;
            return newSq;
        }
        //将Square转换成int
        public static explicit operator int(Square s)
        {
            return s.Length;
        }
    }
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle(15, 4);
        Square s = (Square)r;

        Rectangle rect = new Rectangle(10, 5);
        Square sq2 = (Square)90;

        int side = (int)sq2;

        //implicit
        Square s3;
        s3.Length = 7;
        Rectangle rect2 = s3;

        //explicit
        Square s4;
        s4.Length = 3;
        Rectangle rect3 = (Rectangle)s4;
    }

六:不安全代码设置,unsafe
    public unsafe struct Node
    {
        public int Value;
        public Node* Left;
        public Node* Right;
    }
    public struct Node2
    {
        public int Value;
        public unsafe Node2* Left;
        public unsafe Node2* Right;
    }
    struct Point
    {
        public int x;
        public int y;
        public override string ToString()
        {
            return string.Format("({0}, {1})", x, y);
        }
    }
    class PointRef
    {
        public int x;
        public int y;
        public override string ToString()
        {
            return string.Format("({0}, {1})", x, y);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            int i = 10, j = 20;
            SafeSwap(ref i, ref j);

            unsafe
            {
                UnsafeSwap(&i, &j);
            }

            UsePointerToPoint();
 
            UseSizeOfOperator();

        }

        public static void SafeSwap(ref int i, ref int j)
        {
            int temp = i;
            i = j;
            j = temp;
        }

        unsafe public static void UnsafeSwap(int* i, int* j)
        {
            int temp = *i;
            *i = *j;
            *j = temp;
        }

        unsafe static void PrintValueAndAddress()
        {
            int myInt;
            int* ptrToMyInt = &myInt;
            *ptrToMyInt = 123;
            Console.WriteLine("Value of myInt {0}", myInt);
            Console.WriteLine("Address of myInt {0:X}", (int)&ptrToMyInt);
        }

        unsafe static void SquareIntPointer(int* myIntPointer)
        {
            *myIntPointer *= *myIntPointer;
        }

        unsafe static void UsePointerToPoint()
        {
            Point point;
            Point* p = &point;
            p->x = 100;
            p->y = 200;
            Console.WriteLine(p->ToString());

            Point point2;
            Point* p2 = &point2;
            (*p2).x = 100;
            (*p2).y = 200;
            Console.WriteLine((*p2).ToString());
        }

        //C#提供一个的关键字stackalloc用于申请堆栈内存。
        //注意,这个申请内存分配的是栈内存,当函数执行完毕后,内存会被自动回收。
        //不过我想用这个栈内存基本可以解决40%的问题,而且使用的时候不必担心内存泄漏问题。
        unsafe static void UnsafeStackAlloc()
        {
            char* p = stackalloc char[256];
            for (int k = 0; k < 256; k++)
                p[k] = (char)k;
        }

        unsafe public static void UseAndPinPoint()
        {
            PointRef pt = new PointRef();
            pt.x = 5;
            pt.y = 6;

            fixed (int* p = &pt.x)
            {
                // Use int* variable here!
            }
            Console.WriteLine("Point is: {0}", pt);
        }

        unsafe static void UseSizeOfOperator()
        {
            Console.WriteLine("The size of short is {0}.", sizeof(short));
            Console.WriteLine("The size of int is {0}.", sizeof(int));
            Console.WriteLine("The size of long is {0}.", sizeof(long));
            Console.WriteLine("The size of Point is {0}.", sizeof(Point));
        }
    }

你可能感兴趣的:(object,String,struct,equals,Class,Dictionary)