Condividi tramite


Procedura: differenza tra il passaggio a un metodo di una struttura e di un riferimento a una classe (Guida per programmatori C#)

Aggiornamento: novembre 2007

In questo esempio viene mostrato che quando si passa una struttura a un metodo viene passata una copia della struttura, mentre quando si passa un'istanza di una classe viene passato un riferimento.

L'output dell'esempio riportato di seguito mostra che quando l'istanza della classe viene passata al metodo ClassTaker, cambia solo il valore del campo della classe. Il campo della struttura non subisce alcuna modifica nel passaggio della relativa istanza al metodo StructTaker. Il motivo è che al metodo StructTaker viene passata una copia della struttura, mentre al metodo ClassTaker viene passato un riferimento alla classe.

Esempio

class TheClass
{
    public string willIChange;
}

struct TheStruct
{
    public string willIChange;
}

class TestClassAndStruct
{
    static void ClassTaker(TheClass c)
    {
        c.willIChange = "Changed";
    }

    static void StructTaker(TheStruct s)
    {
        s.willIChange = "Changed";
    }

    static void Main()
    {
        TheClass testClass = new TheClass();
        TheStruct testStruct = new TheStruct();

        testClass.willIChange = "Not Changed";
        testStruct.willIChange = "Not Changed";

        ClassTaker(testClass);
        StructTaker(testStruct);

        Console.WriteLine("Class field = {0}", testClass.willIChange);
        Console.WriteLine("Struct field = {0}", testStruct.willIChange);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Class field = Changed
    Struct field = Not Changed
*/

Vedere anche

Concetti

Guida per programmatori C#

Riferimenti

Classi (Guida per programmatori C#)

Strutture (Guida per programmatori C#)

Passaggio di parametri (Guida per programmatori C#)