martedì 12 luglio 2011

How To: Create and use struct

Potrebbe essere opportuno comprendere le differenze fra una "class" e un "struct".

Di concetto la prima è un oggetto e in quanto tale potrebbe / dovrebbe essere utilizzata non solo per definire un dato o un insieme di dati, ma anche una possibile porzione di logica di gestione.
Oppure potrebbe non rappresentare dati ma insiemi di funzionalità. A tal proposito in una calsse possono essere implementati i metodi, eventi, deglegati e quanto di più necessario alla gestione degli stessi.

Una struct serve per rappresentare "un tipo di dati", semplice semplice, tanto è vero che generalmente una struttura difficilmente contiene metodi differenti da "operatori".

Questo esempio mostra il comportamento di una struct.

class Program
{


static void Main(string[] args)
{
sampleStruct s = new sampleStruct(5, 5);

Console.WriteLine(s.ToString());
s++;

Console.WriteLine(s.ToString());

sampleStruct s1 = new sampleStruct(4, 4);

s = s + s1;
Console.WriteLine(s.ToString());

if (s1.Equals(s))
{
Console.WriteLine(" s = s1 !");
}


Console.ReadLine();
}

}

public struct sampleStruct
{
private int _x;
private int _y;

public int x
{
get { return _x; }
set { _x = value; }
}
public int y
{
get { return _y; }
set { _y = value; }
}

public sampleStruct(int X, int Y)
{
_x = X;
_y = Y;
}

public static sampleStruct operator +(sampleStruct s1, sampleStruct s2)
{
s1.x = s1.x + s2.x;
s1.y = s1.y + s2.y;

return s1;
}

public static sampleStruct operator ++(sampleStruct s)
{
s.x = s.x + 1;
s.y = s.y + 1;

return s;
}

public override bool Equals(object obj)
{
if ((this.x != null) && (this.y != null))
{
try
{
sampleStruct s0 = (sampleStruct)obj;

if (( s0.x == this.x) && ( s0.y==this.y))
{
return true;
}

return false;
}
catch
{
return false;
}
}
return false;
}

public override string ToString()
{
if ((this.x != null) && (this.y != null))
{
return "(" + this.x + " " + this.y + ")";
}
else
{
return "(0,0)";
}
}
}



Questa struttura presenta due proprietà (X,Y), presenta :
operatore + ( somma )
operatore ++ ( incremento naturale )
override di ToString ( utile per comprendere il contenuto della struct )
override di Equals ( per le comparazioni )

Nessun commento: