In generale, leggere my article about parameter passing.
L'idea di base è:
Se l'argomento viene passato per riferimento, quindi modifica al valore del parametro all'interno del metodo influenzerà l'argomento pure.
La parte sottile è che se il parametro è un tipo di riferimento, quindi facendo:
someParameter.SomeProperty = "New Value";
non è modificare il valore del parametro. Il parametro è solo un riferimento e quanto sopra non modifica ciò a cui fa riferimento il parametro, ma solo i dati all'interno dell'oggetto. Ecco un esempio di realmente cambiare il valore del parametro:
someParameter = new ParameterType();
Ora per gli esempi:
semplice esempio: passare un int da ref o per valore
class Test
{
static void Main()
{
int i = 10;
PassByRef(ref i);
// Now i is 20
PassByValue(i);
// i is *still* 20
}
static void PassByRef(ref int x)
{
x = 20;
}
static void PassByValue(int x)
{
x = 50;
}
}
Più complicato esempio: utilizzo dei tipi di riferimento
class Test
{
static void Main()
{
StringBuilder builder = new StringBuilder();
PassByRef(ref builder);
// builder now refers to the StringBuilder
// constructed in PassByRef
PassByValueChangeContents(builder);
// builder still refers to the same StringBuilder
// but then contents has changed
PassByValueChangeParameter(builder);
// builder still refers to the same StringBuilder,
// not the new one created in PassByValueChangeParameter
}
static void PassByRef(ref StringBuilder x)
{
x = new StringBuilder("Created in PassByRef");
}
static void PassByValueChangeContents(StringBuilder x)
{
x.Append(" ... and changed in PassByValueChangeContents");
}
static void PassByValueChangeParameter(StringBuilder x)
{
// This new object won't be "seen" by the caller
x = new StringBuilder("Created in PassByValueChangeParameter");
}
}
fonte
2009-08-18 10:48:03
Duplicato http://stackoverflow.com/questions/373419/whats-the-difference-between-a-parameter-passed-by-reference-vs-passed-by-value –
Questo è * una specie di * un duplicato, ma questo in particolare richiede esempi C# - mentre non ci sono esempi C# nella domanda di riferimento. Un bel po 'di discussione * generale *, certamente, ma non credo che faccia male avere anche quelli specifici per la lingua. –
@Jon Skeet: non è la soluzione giusta per inserire una risposta con la sintassi C# nella domanda esistente? Presumibilmente modificando una risposta esistente. – dmckee