ICloneable

Filed Under (Uncategorized) by nameless on 07-08-2009

Klónozható objektumok (ICloneable):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace CloneablePoint
{
    public class Point : ICloneable
    {
        public int x, y;
        public Point(int x, int y) { this.x = x; this.y = y; }
        public Point() { }
 
        //Az aktuális objektum máslatát adja vissza
        public object Clone()
        { return new Point(this.x, this.y); }
 
        //Az Object.ToString felülbírálása
        public override string ToString()
        { return(string.Format("x = {0}; y = {1}",x,y)); }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            //A Clone generikus objektumot ad vissza
            //Eplicit kasztolással olvasható ki a leszármazott típus
            var p3 = new Point(100, 100);
            Point p4 = (Point)p3.Clone();
 
            //a p4.x megváltoztatása
            p4.x = 0;
            Console.WriteLine(p3);
            Console.WriteLine(p4);
 
            Console.ReadKey();
        }
    }
}

Post a comment