En general, lea my article about parameter passing.
La idea básica es:
Si el argumento se pasa por referencia, a continuación, cambia al valor del parámetro en el método afectará el argumento también.
La parte sutil es que si el parámetro es un tipo de referencia, a continuación, haciendo:
someParameter.SomeProperty = "New Value";
no es cambiando el valor del parámetro. El parámetro es solo una referencia, y lo anterior no cambia a qué se refiere el parámetro, solo los datos dentro del objeto. Aquí está un ejemplo de genuinamente cambiar el valor del parámetro:
someParameter = new ParameterType();
ahora por ejemplos:
ejemplo simple: hacer pasar un int por ref o por valor
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;
}
}
más complicado ejemplo: utilizando los tipos de referencia
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");
}
}
Duplicado http://stackoverflow.com/questions/373419/whats-the-difference-between-a-parameter-passed-by-reference-vs-passed-by-value –
Eso es * un tipo de * un duplicado, pero esto específicamente solicita ejemplos de C#, mientras que no hay ejemplos de C# en absoluto en la pregunta a la que se hace referencia. Una gran cantidad de buenas discusiones * generales *, sin duda, pero no creo que realmente lastime tener las específicas del lenguaje también. –
@Jon Skeet: ¿No es la solución correcta insertar una respuesta con sintaxis C# en la pregunta existente? Presumiblemente editando una respuesta existente. – dmckee