方法参数修饰
(啥也没有) 如果参数的修饰是啥也没有,那么其参数传递的方式是值传递,接受方收到的是原始数据的拷贝
out 说明了参数是引用传递。
params 可变参,注意了这种修饰符针对的参数一定是最后一个参数
ref 引用传递,参数的内容会改变。
// 缺省是传值
public static int Add(int x, int y)
{
int ans = x + y;
x = 10000;
y = 88888;
return ans;
}
static void Main(string[] args)
{
int x = 9, y = 10;
Console.WriteLine("调用前: X: {0}, Y: {1}", x, y);
Console.WriteLine("结果: {0}", Add(x, y));
Console.WriteLine("调用后: X: {0}, Y: {1}", x, y);
}
// 输出修饰
public static void Add(int x, int y, out int ans)
{
ans = x + y;
}
static void Main(string[] args)
{
// 不需要进行本地赋值
int ans;
Add(90, 90, out ans);
Console.WriteLine("90 + 90 = {0} ", ans);
}
// 多个输出修饰
public static void FillTheseValues(out int a, out string b, out bool c)
{
a = 9;
b = "Enjoy your string.";
c = true;
}
static void Main(string[] args)
{
int i;
string str;
bool b;
FillTheseValues(out i, out str, out b);
Console.WriteLine("Int is: {0}", i);
Console.WriteLine("String is: {0}", str);
Console.WriteLine("Boolean is: {0}", b);
}
//引用修饰
public static void SwapStrings(ref string s1, ref string s2)
{
string tempStr = s1;
s1 = s2;
s2 = tempStr;
}
This method can be called as so:
static void Main(string[] args)
{
string s = "第一个字符串";
string s2 = "其他字符串";
Console.WriteLine("之前: {0}, {1} ", s, s2);
SwapStrings(ref s, ref s2);
Console.WriteLine("之后: {0}, {1} ", s, s2);
}
//可变参
static double CalculateAverage(params double[] values)
{
double sum = 0;
for (int i = 0; i < values.Length; i++)
sum += values[i];
return (sum / values.Length);
}
static void Main(string[] args)
{
// Pass in a comma-delimited list of doubles...
double average;
average = CalculateAverage(4.0, 3.2, 5.7);
Console.WriteLine("4.0, 3.2, 5.7 的平均数是: {0}",
average);
double[] data = { 4.0, 3.2, 5.7 };
average = CalculateAverage(data);
Console.WriteLine("Average of data is: {0}", average);
Console.ReadLine();
}