Mer*_*ğul 3 c# parameters methods parameter-passing pass-by-reference
我一直在努力研究C#方法.有三种方法可以将参数传递给C#方法.
值参数:此方法将参数的实际值复制到函数的形式参数中.在这种情况下,对函数内部参数所做的更改对参数没有影响.
引用参数:此方法将对参数的内存位置的引用复制到形参中.这意味着对参数所做的更改会影响参数.
输出参数:此方法有助于返回多个值.
我通过以下示例代码了解了上述类型的传递参数.
using System;
namespace PassingParameterByReference
{
class MethodWithReferenceParameters
{
public void swap(ref int x)
{
int temp = 5;
x = temp;
}
static void Main(string[] args)
{
MethodWithReferenceParameters n = new MethodWithReferenceParameters();
/* local variable definition */
int a = 100;
Console.WriteLine("Before swap, value of a : {0}", a);
/* calling a function to swap the value*/
n.swap(ref a);
Console.WriteLine("After swap, value of a : {0}", a);
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译并执行上述代码时,会产生以下结果:
在交换之前,a的值为:100
交换后,a:5的值
使用此代码,我可以理解通过引用将参数传递给方法.然后我检查下面的代码,以了解输出方法的传递参数.
using System;
namespace PassingParameterByOutput
{
class MethodWithOutputParameters
{
public void swap(out int x)
{
int temp = 5;
x = temp;
}
static void Main(string[] args)
{
MethodWithOutputParameters n = new MethodWithOutputParameters();
/* local variable definition */
int a = 100;
Console.WriteLine("Before swap, value of a : {0}", a);
/* calling a function to swap the value */
n.swap(out a);
Console.WriteLine("After swap, value of a : {0}", a);
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译并执行上述代码时,会产生以下结果:
在交换之前,a的值为:100
交换后,a:5的值
这些示例代码以不同的方式执行相同的操作.并且我无法理解两种方法之间的区别.(通过输出和参考将参数传递给方法).两个例子的输出是相同的.这个小差异是什么?
在调用方法之前不必初始化输出参数,就像参考参数的情况一样.
int someNum;
someMethod(out someNum); //works
someMethod(ref someNum); //gives compilation error
Run Code Online (Sandbox Code Playgroud)
此外,需要在方法中设置或更改输出参数,这对于参考参数不是必需的.