yield használata

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

yield használata:

using System;
using System.Collections;
using System.Collections.Generic;
 
namespace Program
{
    class ArrayClass : IEnumerable
    {
        int[] array = { 23, 34, 5643, 56767 };
 
        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < array.Length; i++) //végigpörgetük a tömb elemeit
                yield return array[i]; //visszaadjuk a tömb adott elemét a yield return segítségével
        }
    }
    class MainClass
    {
        public static void Main()
        {
            var myA = new ArrayClass();
 
            foreach (var i in myA)
            {
                Console.WriteLine(i);
            }
 
            Console.ReadKey();
        }
    }
}

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();
        }
    }
}

IEnumerable

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

Az IEnumerable segít a foreach asználatában.

using System;
using System.Collections; //Ez fontos
 
namespace Program
{
 
    // Az adott osztálynak teljesítenie kell a IEnumerable interfész GEnumerator() metódusát
    class ArrayClass : IEnumerable
    {
        int[] array = { 23, 34, 5643, 56767 };
 
        public IEnumerator GetEnumerator()
        {
           return array.GetEnumerator();
        }
    }
    class MainClass
    {
        public static void Main()
        {
            var myA = new ArrayClass();
 
            foreach (var i in myA)
            {
                Console.WriteLine(i);
            }
            Console.ReadKey();
        }
 
    }
}

Felsorolható típusok készítése

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

Felsorolható típusok készítése (IEnumerator, IEnumerable):

rádió osztály:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace CustomEnumerator
{
  public class Radio
  {
    public void TurnOn(bool on)
    {
      if(on)
        Console.WriteLine("Jamming...");
      else
        Console.WriteLine("Quiet time...");
    }
  }
}

garage osztály:

using System;
using System.Collections.Generic;
using System.Text;
 
// Need this for IEnumerator
using System.Collections;
 
namespace CustomEnumerator
{
  // Garage contains a set of Car objects.
  public class Garage : IEnumerable
  {
    private Car[] carArray= new Car[4];
 
    // Fill with some Car objects upon startup.
    public Garage()
    {
      carArray[0] = new Car("Rusty", 30);
      carArray[1] = new Car("Clunker", 55);
      carArray[2] = new Car("Zippy", 30);
      carArray[3] = new Car("Fred", 30);
    }
 
    #region IEnumerable Members
 
    public IEnumerator GetEnumerator()
    {
      return carArray.GetEnumerator();
    }
 
    #endregion
  }
}

car osztály:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace CustomEnumerator
{
  public class Car
  {
    #region Member variables & Constructors
    // Constant for maximum speed.
    public const int MaxSpeed = 100;
 
    // Internal state data.
    private int currSpeed;
    private string petName;
 
    // Is the car still operational?
    private bool carIsDead;
 
    // A car has-a radio.
    private Radio theMusicBox = new Radio();
 
    // Constructors.
    public Car() {}
    public Car(string name, int currSp)
    {
      currSpeed = currSp;
      petName = name;
    }
    #endregion
 
    #region Properties
    public int Speed
    {
      get { return currSpeed; }
      set { currSpeed = value; }
    }
    public string PetName
    {
      get { return petName; }
      set { petName = value; }
    }	
    #endregion
 
    #region Methods
    public void CrankTunes(bool state)
    {
      // Delegate request to inner object.
      theMusicBox.TurnOn(state);
    }
 
    // This time, throw an exception if the user speeds up beyond MaxSpeed.
    public void Accelerate(int delta)
    {
      if (carIsDead)
        Console.WriteLine("{0} is out of order...", petName);
      else
      {
        currSpeed += delta;
        if (currSpeed >= MaxSpeed)
        {
          carIsDead = true;
          currSpeed = 0;
 
          // We need to call the HelpLink property, thus we need
          // to create a local variable before throwing the Exception object.
          Exception ex =
            new Exception(string.Format("{0} has overheated!", petName));
          ex.HelpLink = "http://www.CarsRUs.com";
 
          // Stuff in custom data regarding the error.
          ex.Data.Add("TimeStamp",
            string.Format("The car exploded at {0}", DateTime.Now));
          ex.Data.Add("Cause", "You have a lead foot.");
          throw ex;
        }
        else
          Console.WriteLine("=> CurrSpeed = {0}", currSpeed);
      }
    }
    #endregion
  }
}

program osztály:

using System;
using System.Collections.Generic;
using System.Text;
 
using System.Collections;
 
namespace CustomEnumerator
{
  // This seems reasonable...
  public class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("***** Fun with IEnumerable / IEnumerator *****\n");
 
      Garage carLot = new Garage();
 
      // Hand over each car in the collection?
      foreach (Car c in carLot)
      {
        Console.WriteLine("{0} is going {1} MPH",
          c.PetName, c.Speed);
      }
 
      Console.WriteLine();
 
      // Manually work with IEnumerator.
      IEnumerator i = carLot.GetEnumerator();
      i.MoveNext();
      Car myCar = (Car)i.Current;
      Console.WriteLine("{0} is going {1} MPH", myCar.PetName, myCar.Speed);
      Console.ReadLine();
    }
  }
}

Interfészhiearchia

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

Interfészhiearchia tervezése:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace InterfaceHierarchy
{
    public interface IDrawable
    {
        void Draw();
    }
 
    public interface Iprintable : IDrawable
    {
        void Print();
    }
 
    public interface IRenderToMemory : Iprintable
    {
        void Render();
    }
 
    public class SuperShape : IRenderToMemory
    {
        public void Draw()
        {
            Console.WriteLine("Drawing...");
        }
        public void Print()
        {
            Console.WriteLine("Printig...");
        }
        public void Render()
        {
            Console.WriteLine("Rendering...");
        }
    }
    public class TwoShape : Iprintable
    {
        public void Draw()
        {
            Console.WriteLine("Drawing...");
        }
        public void Print()
        {
            Console.WriteLine("Printig...");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("**********SUPERSHAPE*************");
            var myShape = new SuperShape();
            myShape.Draw();
            myShape.Print();
            myShape.Render();
 
            Console.ReadKey();
 
            Console.WriteLine("\n\n************TwoShape*************");
            var myTwoShape = new TwoShape();
            myTwoShape.Draw();
            myTwoShape.Print();
 
            Console.ReadKey();
        }
    }
}

Többszörös interface öröklés

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

Töbszörös öröklés interfészekkel:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace MIInterfaceHierarchy
{
    #region interface-k
    //az interfészek többszöri öröklése működik
    public interface IDrawable
    {
        void Draw();
    }
 
    public interface Iprintable
    {
        void Print();
        void Draw(); // <-- Lehetséges névtükrözés
    }
 
    //Többszörös öröklés interészekkel
    public interface IShape : IDrawable, Iprintable
    {
        int GetNumberOfSides();
    }
    #endregion
 
    #region megvalosito osztalyok
    class Rectangle : IShape
    {
        public int GetNumberOfSides()
        { return 4; }
 
        public void Draw()
        { Console.WriteLine("Drawing..."); }
 
        public void Print()
        { Console.WriteLine("Printing..."); }
    }
 
    class Square : IShape
    {
        void IDrawable.Draw()
        { Console.WriteLine("IDrawable Drawing..."); }
 
        void Iprintable.Draw()
        { Console.WriteLine("Iprintable Drawing..."); }
 
        public void Print()
        { Console.WriteLine("Printing..."); }
 
        public int GetNumberOfSides()
        { return 4; }
    }
    #endregion
 
    class Program
    {
        static void Main(string[] args)
        {
            var myRectangle = new Rectangle();
            myRectangle.Draw();
            myRectangle.Print();
            Console.WriteLine("{0}\n",myRectangle.GetNumberOfSides());
 
            Console.ReadKey();
 
            var mySquare = new Square();
            mySquare.Print();
            Console.WriteLine(mySquare.GetNumberOfSides());
            ((IDrawable)mySquare).Draw();
            ((Iprintable)mySquare).Draw();
 
            Console.ReadKey();
        }
    }
}

Interface névütközés

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

Névütközés feloldása explicit interfészimplementációval:

using System;
 
namespace egyformaInterfacek
{
 
    #region Interfacek
    interface IAutoSebesseg
    {
        void Kiir();
    }
 
    interface IMotorSebesseg
    {
        void Kiir();
    }
 
    interface IBuszSebesseg
    {
        void Kiir();
    }
 
    interface IBicikliSebesseg
    {
        void Kiir();
    }
    #endregion
 
    #region Interfacek megvalositasa
    class JarmuvekSebessege : IAutoSebesseg, IBicikliSebesseg, IBuszSebesseg, IMotorSebesseg
    {
        //Ez autómatikusan privát, mivel ha úgy hívnánk meg akkor nem lehetne eldönteni melyiket is akarjuk kiírni
        void IAutoSebesseg.Kiir()
        {
            Console.WriteLine("320km/h");
        }
        void IBicikliSebesseg.Kiir()
        {
            Console.WriteLine("Attol fugg ki hajtja");
        }
        void IBuszSebesseg.Kiir()
        {
            Console.WriteLine("60km/h");
        }
        void IMotorSebesseg.Kiir()
        {
            Console.WriteLine("290km/h");
        }
    }
    #endregion
 
    class MainClass
    {
        public static void Main()
        {
            var sebesseg = new JarmuvekSebessege();
            ((IAutoSebesseg)sebesseg).Kiir();
            ((IBicikliSebesseg)sebesseg).Kiir();
            ((IBuszSebesseg)sebesseg).Kiir();
            ((IMotorSebesseg)sebesseg).Kiir();
 
            Console.ReadKey();
        }
    }
}

Microsoft formális, prim and proper feszabadítási minta

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

A Microsoft formális, prim and proper feszabadítási mintát definiált, amely megteremti a robusztusság, a fenntarthatóság és a teljesítmény kzöti egyensúlyt:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace FinalizableDisposableClass
{
  public class MyResourceWrapper : IDisposable
  {
    //annak a megállapítására használatos, hogy a Dispose() már meghívásra került-e
    private bool disposed = false;
 
    public void Dispose()
    {
      //segédmetódus meghívása
      //A true érték at jez, hogy az objektumfelhasználó elindította a takarítást
      CleanUp(true);
 
      // Most szüntessük meg a véglegesítést.
      GC.SuppressFinalize(this);
    }
 
    private void CleanUp(bool disposing)
    {
      // Bizonyosodjunk meg róla, hogy még nem dobtunk el semmit.
      if (!this.disposed)
      {
        // Ha az eldobás igaz értéket eredményez, akkor dobjuk el az összes felügyelt erőforrást
        if (disposing)
        {
            // felügyelt erőforrás eldobása
        }
        // Itt kitakarítjuk a nem felügyelt erőforrásokat
      }
      disposed = true;
    }
 
    ~MyResourceWrapper()
    {
      Console.Beep();
      // A segédmetódusunk meghívása
      // A false érték azt jelzi, hogy a GC eindította a takarítást
      CleanUp(false);
    }
  }
 
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("***** Dispose() / Destructor Combo Platter *****");
 
      // A Dispose() manuális meghívása, ez nem hívja meg a véglegesítőt.
      MyResourceWrapper rw = new MyResourceWrapper();
      rw.Dispose();
 
      // Ez nem a Dispose() metódust hívja meg, hanem elindítja a véglegesítőt és sípolást
      MyResourceWrapper rw2 = new MyResourceWrapper();
    }
  }
}

Formalizát && eldobható objektumok

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

Read the rest of this entry »

Eldobható objektumok

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

Ahhoz hogy eldobható objektumot hozzunk létre meg kell valósítanunk az IDisposable interfészt, melynek egyedüli tagja a Dispose()

public interface IDisposable
{
     void Dispose();
}
 
egy összetetteb példa:
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SimpleDispose
{
    public interface IDisposable
    {
        void Dispose();
    }
 
    public class MyResourceWrapper : IDisposable
    {
        //az objektum használójának meg kell hívni ezt a metódust, ha befejezte az objektum használatát
        public void Dispose()
        {
            //nem felügyelt erőforrások kitakarítása
 
            //más tartalmazott eldobható objektumok eldobása...
 
            Console.WriteLine("In dospose!");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var myDispos = new MyResourceWrapper();
            myDispos.Dispose();
 
            Console.ReadKey();
        }
    }
}